-
-
Save merolhack/3b242fac97e4167ec2be to your computer and use it in GitHub Desktop.
Javascript Slugify: For accents and other latin characters
This file contains 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
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 - | |
} |
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
A more functional approach