31 lines
562 B
JavaScript
31 lines
562 B
JavaScript
'use strict';
|
|
|
|
function slugify(string, delimiter = '-', {
|
|
encode = false,
|
|
limit = 1000,
|
|
} = {}) {
|
|
if (!string || typeof string !== 'string') {
|
|
return string;
|
|
}
|
|
|
|
const slugComponents = string.trim().toLowerCase().match(/\w+/g);
|
|
|
|
if (!slugComponents) {
|
|
return '';
|
|
}
|
|
|
|
const slug = slugComponents.reduce((acc, component, index) => {
|
|
const accSlug = `${acc}${index > 0 ? delimiter : ''}${component}`;
|
|
|
|
if (accSlug.length < limit) {
|
|
return accSlug;
|
|
}
|
|
|
|
return acc;
|
|
}, '');
|
|
|
|
return encode ? encodeURI(slug) : slug;
|
|
}
|
|
|
|
module.exports = slugify;
|