slugize.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. const escapeDiacritic = require('./escape_diacritic');
  3. const escapeRegExp = require('./escape_regexp');
  4. // eslint-disable-next-line no-control-regex
  5. const rControl = /[\u0000-\u001f]/g;
  6. const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'<>,.?/]+/g;
  7. function slugize(str, options = {}) {
  8. if (typeof str !== 'string') throw new TypeError('str must be a string!');
  9. const separator = options.separator || '-';
  10. const escapedSep = escapeRegExp(separator);
  11. const result = escapeDiacritic(str)
  12. // Remove control characters
  13. .replace(rControl, '')
  14. // Replace special characters
  15. .replace(rSpecial, separator)
  16. // Remove continous separators
  17. .replace(new RegExp(`${escapedSep}{2,}`, 'g'), separator)
  18. // Remove prefixing and trailing separtors
  19. .replace(new RegExp(`^${escapedSep}+|${escapedSep}+$`, 'g'), '');
  20. switch (options.transform) {
  21. case 1:
  22. return result.toLowerCase();
  23. case 2:
  24. return result.toUpperCase();
  25. default:
  26. return result;
  27. }
  28. }
  29. module.exports = slugize;