index.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import escapeStringRegexp from 'escape-string-regexp';
  2. import transliterate from '@sindresorhus/transliterate';
  3. import builtinOverridableReplacements from './overridable-replacements.js';
  4. const decamelize = string => {
  5. return string
  6. // Separate capitalized words.
  7. .replace(/([A-Z]{2,})(\d+)/g, '$1 $2')
  8. .replace(/([a-z\d]+)([A-Z]{2,})/g, '$1 $2')
  9. .replace(/([a-z\d])([A-Z])/g, '$1 $2')
  10. // `[a-rt-z]` matches all lowercase characters except `s`.
  11. // This avoids matching plural acronyms like `APIs`.
  12. .replace(/([A-Z]+)([A-Z][a-rt-z\d]+)/g, '$1 $2');
  13. };
  14. const removeMootSeparators = (string, separator) => {
  15. const escapedSeparator = escapeStringRegexp(separator);
  16. return string
  17. .replace(new RegExp(`${escapedSeparator}{2,}`, 'g'), separator)
  18. .replace(new RegExp(`^${escapedSeparator}|${escapedSeparator}$`, 'g'), '');
  19. };
  20. const buildPatternSlug = options => {
  21. let negationSetPattern = 'a-z\\d';
  22. negationSetPattern += options.lowercase ? '' : 'A-Z';
  23. if (options.preserveCharacters.length > 0) {
  24. for (const character of options.preserveCharacters) {
  25. if (character === options.separator) {
  26. throw new Error(`The separator character \`${options.separator}\` cannot be included in preserved characters: ${options.preserveCharacters}`);
  27. }
  28. negationSetPattern += escapeStringRegexp(character);
  29. }
  30. }
  31. return new RegExp(`[^${negationSetPattern}]+`, 'g');
  32. };
  33. export default function slugify(string, options) {
  34. if (typeof string !== 'string') {
  35. throw new TypeError(`Expected a string, got \`${typeof string}\``);
  36. }
  37. options = {
  38. separator: '-',
  39. lowercase: true,
  40. decamelize: true,
  41. customReplacements: [],
  42. preserveLeadingUnderscore: false,
  43. preserveTrailingDash: false,
  44. preserveCharacters: [],
  45. ...options
  46. };
  47. const shouldPrependUnderscore = options.preserveLeadingUnderscore && string.startsWith('_');
  48. const shouldAppendDash = options.preserveTrailingDash && string.endsWith('-');
  49. const customReplacements = new Map([
  50. ...builtinOverridableReplacements,
  51. ...options.customReplacements
  52. ]);
  53. string = transliterate(string, {customReplacements});
  54. if (options.decamelize) {
  55. string = decamelize(string);
  56. }
  57. const patternSlug = buildPatternSlug(options);
  58. if (options.lowercase) {
  59. string = string.toLowerCase();
  60. }
  61. // Detect contractions/possessives by looking for any word followed by a `'t`
  62. // or `'s` in isolation and then remove it.
  63. string = string.replace(/([a-zA-Z\d]+)'([ts])(\s|$)/g, '$1$2$3');
  64. string = string.replace(patternSlug, options.separator);
  65. string = string.replace(/\\/g, '');
  66. if (options.separator) {
  67. string = removeMootSeparators(string, options.separator);
  68. }
  69. if (shouldPrependUnderscore) {
  70. string = `_${string}`;
  71. }
  72. if (shouldAppendDash) {
  73. string = `${string}-`;
  74. }
  75. return string;
  76. }
  77. export function slugifyWithCounter() {
  78. const occurrences = new Map();
  79. const countable = (string, options) => {
  80. string = slugify(string, options);
  81. if (!string) {
  82. return '';
  83. }
  84. const stringLower = string.toLowerCase();
  85. const numberless = occurrences.get(stringLower.replace(/(?:-\d+?)+?$/, '')) || 0;
  86. const counter = occurrences.get(stringLower);
  87. occurrences.set(stringLower, typeof counter === 'number' ? counter + 1 : 1);
  88. const newCounter = occurrences.get(stringLower) || 2;
  89. if (newCounter >= 2 || numberless > 2) {
  90. string = `${string}-${newCounter}`;
  91. }
  92. return string;
  93. };
  94. countable.reset = () => {
  95. occurrences.clear();
  96. };
  97. return countable;
  98. }