Last active
April 29, 2024 02:20
-
-
Save swsalim/f7a681a3a734b5251305ea8c62c7e833 to your computer and use it in GitHub Desktop.
A function to slugify string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Typescript | |
const slugify = (str: string) => { | |
// remove accents, swap ñ for n, etc | |
const from = 'àáãäâèéëêìíïîòóöôùúüûñç·/_,:;'; | |
const to = 'aaaaaeeeeiiiioooouuuunc------'; | |
const slug = str.split('').map((letter, i) => { | |
return letter.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
}); | |
return ( | |
// Replace multiple - with single - | |
slug | |
.toString() // Cast to string | |
.toLowerCase() // Convert the string to lowercase letters | |
.trim() // Remove whitespace from both sides of a string | |
.replace(/\s+/g, '-') // Replace spaces with - | |
.replace(/\/+/g, '-') // Replace / with - | |
.replace(/&/g, '-and-') // Replace & with 'and' | |
// eslint-disable-next-line no-useless-escape | |
.replace(/[^\w\-]+/g, '') // Remove all non-word chars | |
// eslint-disable-next-line no-useless-escape | |
.replace(/\-\-+/g, '-') | |
); | |
}; | |
// Javascript | |
export const slugify = (str) => { | |
// remove accents, swap ñ for n, etc | |
const from = 'àáãäâèéëêìíïîòóöôùúüûñç·/_,:;'; | |
const to = 'aaaaaeeeeiiiioooouuuunc------'; | |
const slug = str.split('').map((letter, i) => { | |
return letter.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
}); | |
return ( | |
// Replace multiple - with single - | |
slug | |
.toString() // Cast to string | |
.toLowerCase() // Convert the string to lowercase letters | |
.trim() // Remove whitespace from both sides of a string | |
.replace(/\s+/g, '-') // Replace spaces with - | |
.replace(/\/+/g, '-') // Replace / with - | |
.replace(/&/g, '-and-') // Replace & with 'and' | |
// eslint-disable-next-line no-useless-escape | |
.replace(/[^\w\-]+/g, '') // Remove all non-word chars | |
// eslint-disable-next-line no-useless-escape | |
.replace(/\-\-+/g, '-') | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment