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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import toTitleCase from './toTitleCase'
/**
* Creates a slug from input parameters by converting the name and appending it with an ID.
* The slug is generated by removing special characters, converting to lowercase, and joining with hyphens.
*
* @param {string} prefix - The prefix to be added to the generated slug.
* @param {string} name - The name used to generate the slug.
* @param {number} id - The ID to be appended to the slug.
* @returns {string} - The generated slug with the prefix, name, and ID.
*/
const createSlug = (prefix, name, id, withHost = false) => {
let slug =
name
?.trim()
.replace(new RegExp(/[^A-Za-z0-9]/, 'g'), '-')
.toLowerCase() +
'-' +
id
let splitSlug = slug.split('-')
let filterSlugFromEmptyChar = splitSlug.filter((x) => x != '')
slug = prefix + filterSlugFromEmptyChar.join('-')
if (withHost) slug = process.env.NEXT_PUBLIC_SELF_HOST + slug
return slug
}
/**
* Extracts the ID from a slug.
* The ID is retrieved from the last segment of the slug, separated by hyphens.
*
* @param {string} slug - The slug from which to extract the ID.
* @returns {string} - The extracted ID from the slug.
*/
const getIdFromSlug = (slug) => {
let id = slug.split('-')
return id[id.length - 1]
}
/**
* Extracts the name from a slug.
* The name is retrieved from all segments of the slug, except for the last one, separated by hyphens.
* The retrieved name is then converted to title case.
*
* @param {string} slug - The slug from which to extract the name.
* @returns {string} - The extracted name from the slug in title case.
*/
const getNameFromSlug = (slug) => {
let name = slug.split('-')
name.pop()
return toTitleCase(name.join(' '))
}
export { createSlug, getIdFromSlug, getNameFromSlug }
|