@gouvfr/dsfr-forge
Version:
Le module `dsfr-forge` offre des outils et utilitaires de développement partagés entre les différents modules du Système de Design de l’État - DSFR.
57 lines (51 loc) • 1.82 kB
JavaScript
const LIGATURES_MAP = {
'æ': 'ae',
'Æ': 'AE',
'œ': 'oe',
'Œ': 'OE',
'ß': 'ss',
'ð': 'd',
'Ð': 'D',
'þ': 'th',
'Þ': 'Th',
'ø': 'o',
'Ø': 'O',
'ł': 'l',
'Ł': 'L'
};
const SPECIAL_CHARACTERS_MAP = {
'"': { regex: '"', normalized: '"' },
'$': { regex: '\\$', normalized: '$' },
'&': { regex: '&', normalized: '&' },
"'": { regex: "'", normalized: ''' },
'*': { regex: '\\*', normalized: '*' },
',': { regex: ',', normalized: ',' },
'<': { regex: '<', normalized: '<' },
'>': { regex: '>', normalized: '>' },
'?': { regex: '\\?', normalized: '?' },
'\\': { regex: '\\\\', normalized: '\' },
'^': { regex: '\\^', normalized: '^' },
'`': { regex: '`', normalized: '`' },
'|': { regex: '\\|', normalized: '|' },
'~': { regex: '~', normalized: '~' },
'%': { regex: '%', normalized: '%' },
};
const LIGATURE_REGEX = new RegExp(Object.keys(LIGATURES_MAP).join('|'), 'g');
const SPECIAL_CHARACTERS_REGEX = new RegExp(Object.values(SPECIAL_CHARACTERS_MAP).map(c => c.regex).join('|'), 'g');
// Useful function to normalize strings for URLs
export const normalize = str => str.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[\s'’]/g, '-')
.replace(LIGATURE_REGEX, m => LIGATURES_MAP[m])
.replace(/[^a-z0-9-]/g, '')
.replace(/-+/g, '-')
.replace(/^-/, '')
.replace(/-$/, '');
export const normalizeTerm = str => str.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(LIGATURE_REGEX, m => LIGATURES_MAP[m])
.replace(SPECIAL_CHARACTERS_REGEX, m => SPECIAL_CHARACTERS_MAP[m].normalized);
// Useful function to normalize strings for IDs
export const normalizeId = str => str.replace(/^\//, '').replace(/[^a-zA-Z0-9 \-_.]/g, '.');