-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate_slug.js
39 lines (34 loc) · 1.14 KB
/
generate_slug.js
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
29
30
31
32
33
34
35
36
37
38
39
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
module.exports = function generateSlug(headline, links = []) {
let slug = headline
.toLowerCase()
.trim()
.replace(/<\/?[^>]*>/g, '') // Strip links
.replace(/\(\(#.*?\)\)/g, '') // Strip anchor link aliases
.replace(/\W+/g, '-') // Whitespace to '-'
.replace(/-+/g, '-') // Collapse more than one '-'
.replace(/^\-/g, '') // Remove leading '-'
.replace(/\-$/g, '') // Remove trailing '-'
// count if there are any duplicates on the page
const dupeCount = links.reduce((m, i) => {
if (slug === i) m++
return m
}, 0)
links.push(slug)
// append the count to the end of the slug if necessary
if (dupeCount > 0) slug = `${slug}-${dupeCount}`
return slug
}
module.exports.generateAriaLabel = function generateAriaLabel(headline) {
return headline
.toLowerCase()
.replace(/<\/?[^>]*>/g, '') // Strip html
.replace(/\(\(#.*?\)\)/g, '') // Strip anchor link aliases
.replace(/^\-/g, '') // Remove leading '-'
.replace(/\-$/g, '') // Remove trailing '-'
.replace(/\W+/g, ' ') // Collapse whitespace
.trim()
}