UNPKG

726 BJavaScriptView Raw
1/**
2 * Slugger generates header id
3 */
4module.exports = class Slugger {
5 constructor() {
6 this.seen = {};
7 }
8
9 /**
10 * Convert string to unique id
11 */
12 slug(value) {
13 let slug = value
14 .toLowerCase()
15 .trim()
16 // remove html tags
17 .replace(/<[!\/a-z].*?>/ig, '')
18 // remove unwanted chars
19 .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
20 .replace(/\s/g, '-');
21
22 if (this.seen.hasOwnProperty(slug)) {
23 const originalSlug = slug;
24 do {
25 this.seen[originalSlug]++;
26 slug = originalSlug + '-' + this.seen[originalSlug];
27 } while (this.seen.hasOwnProperty(slug));
28 }
29 this.seen[slug] = 0;
30
31 return slug;
32 }
33};