traxxx/src/utils/slugify.js

77 lines
1.1 KiB
JavaScript
Raw Normal View History

'use strict';
2020-05-26 02:11:29 +00:00
const substitutes = {
à: 'a',
á: 'a',
ä: 'a',
å: 'a',
2020-05-26 23:40:10 +00:00
ã: 'a',
2020-05-26 02:11:29 +00:00
æ: 'ae',
ç: 'c',
è: 'e',
é: 'e',
ë: 'e',
2020-05-26 23:40:10 +00:00
: 'e',
2020-05-26 02:11:29 +00:00
ì: 'i',
í: 'i',
ï: 'i',
2020-05-26 23:40:10 +00:00
ĩ: 'i',
2020-05-26 02:11:29 +00:00
ǹ: 'n',
ń: 'n',
ñ: 'n',
ò: 'o',
ó: 'o',
ö: 'o',
2020-05-26 23:40:10 +00:00
õ: 'o',
2020-05-26 02:11:29 +00:00
ø: 'o',
œ: 'oe',
ß: 'ss',
ù: 'u',
ú: 'u',
ü: 'u',
2020-05-26 23:40:10 +00:00
ũ: 'u',
2020-05-26 02:11:29 +00:00
: 'y',
ý: 'y',
ÿ: 'y',
2020-05-26 23:40:10 +00:00
: 'y',
2020-05-26 02:11:29 +00:00
};
function slugify(string, delimiter = '-', {
encode = false,
2020-05-26 02:11:29 +00:00
removeAccents = true,
removePunctuation = false,
limit = 1000,
} = {}) {
if (!string || typeof string !== 'string') {
return string;
}
const slugComponents = string
.trim()
.toLowerCase()
.replace(removePunctuation && /[.,:;'"_-]/g, '')
.match(/[A-Za-zÀ-ÖØ-öø-ÿ0-9]+/g);
if (!slugComponents) {
return '';
}
const slug = slugComponents.reduce((acc, component, index) => {
const accSlug = `${acc}${index > 0 ? delimiter : ''}${component}`;
if (accSlug.length < limit) {
2020-05-26 02:11:29 +00:00
if (removeAccents) {
2021-11-20 22:59:15 +00:00
return accSlug.replace(/[à-ÿ]/g, (match) => substitutes[match] || '');
2020-05-26 02:11:29 +00:00
}
return accSlug;
}
return acc;
}, '');
2020-01-10 21:10:11 +00:00
return encode ? encodeURI(slug) : slug;
}
module.exports = slugify;