Skip to content

Instantly share code, notes, and snippets.

@merolhack
Forked from mathewbyrne/slugify.js
Last active May 29, 2023 11:30
Show Gist options
  • Save merolhack/3b242fac97e4167ec2be to your computer and use it in GitHub Desktop.
Save merolhack/3b242fac97e4167ec2be to your computer and use it in GitHub Desktop.
Javascript Slugify: For accents and other latin characters
function slugify(text)
{
var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
var to = "aaaaaeeeeeiiiiooooouuuunc------";
_.each( from, function( character, i ) {
text = text.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
});
return text
.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, '-y-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
@radames
Copy link

radames commented Jul 10, 2020

This works for me

function slugify(text) {
    const from = 'ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;'
    const to = 'aaaaaeeeeeiiiiooooouuuunc------'

    const newText = Array.from(s)
      .map((c) => {
        const index = [...from].indexOf(c)
        if (index > -1) {
          return c.replace(
            new RegExp(from.charAt(index), 'g'),
            to.charAt(index)
          )
        }
        return c
      })
      .join('')


    return newText
      .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, '-y-')           // Replace & with 'and'
      .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
      .replace(/\-\-+/g, '-');        // Replace multiple - with single -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment