-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathslugify.ts
28 lines (26 loc) · 948 Bytes
/
slugify.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// string.js slugify drops non ascii chars so we have to
// use a custom implementation here
// eslint-disable-next-line no-control-regex
const rControl = /[\u0000-\u001f]/g
const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'“”‘’–—<>,.?/]+/g
const rCombining = /[\u0300-\u036F]/g
export = function slugify (str: string): string {
// Split accented characters into components
return str.normalize('NFKD')
// Remove links, just leave hyperlink's text
.replace(/^\[(.*)?(]\(.*?\))$/g,'$1')
// Remove accents
.replace(rCombining, '')
// Remove control characters
.replace(rControl, '')
// Replace special characters
.replace(rSpecial, '-')
// Remove continuous separators
.replace(/\-{2,}/g, '-')
// Remove prefixing and trailing separators
.replace(/^\-+|\-+$/g, '')
// ensure it doesn't start with a number (#121)
.replace(/^(\d)/, '_$1')
// lowercase
.toLowerCase()
}