2020-01-07 03:23:28 +00:00
|
|
|
'use strict';
|
|
|
|
|
2020-03-16 03:10:52 +00:00
|
|
|
function slugify(string, delimiter = '-', {
|
2020-02-04 02:12:09 +00:00
|
|
|
encode = false,
|
|
|
|
limit = 1000,
|
|
|
|
} = {}) {
|
2020-03-22 02:50:24 +00:00
|
|
|
if (!string) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2020-02-04 02:12:09 +00:00
|
|
|
const slugComponents = string.trim().toLowerCase().match(/\w+/g);
|
|
|
|
|
2020-03-16 03:10:52 +00:00
|
|
|
if (!slugComponents) {
|
|
|
|
return '';
|
|
|
|
}
|
2020-02-20 01:35:23 +00:00
|
|
|
|
2020-02-04 02:12:09 +00:00
|
|
|
const slug = slugComponents.reduce((acc, component, index) => {
|
|
|
|
const accSlug = `${acc}${index > 0 ? delimiter : ''}${component}`;
|
|
|
|
|
|
|
|
if (accSlug.length < limit) {
|
|
|
|
return accSlug;
|
|
|
|
}
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, '');
|
2020-01-10 21:10:11 +00:00
|
|
|
|
|
|
|
return encode ? encodeURI(slug) : slug;
|
2020-01-07 03:23:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = slugify;
|