Skip to content

Instantly share code, notes, and snippets.

@swsalim
Last active April 29, 2024 02:20
Show Gist options
  • Save swsalim/f7a681a3a734b5251305ea8c62c7e833 to your computer and use it in GitHub Desktop.
Save swsalim/f7a681a3a734b5251305ea8c62c7e833 to your computer and use it in GitHub Desktop.
A function to slugify string
// 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