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 }