Last active
September 4, 2024 02:45
-
-
Save hagemann/382adfc57adbd5af078dc93feef01fe1 to your computer and use it in GitHub Desktop.
Slugify makes a string URI-friendly
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(string) { | |
const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìıİłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;' | |
const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------' | |
const p = new RegExp(a.split('').join('|'), 'g') | |
return string.toString().toLowerCase() | |
.replace(/\s+/g, '-') // Replace spaces with - | |
.replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters | |
.replace(/&/g, '-and-') // Replace & with 'and' | |
.replace(/[^\w\-]+/g, '') // Remove all non-word characters | |
.replace(/\-\-+/g, '-') // Replace multiple - with single - | |
.replace(/^-+/, '') // Trim - from start of text | |
.replace(/-+$/, '') // Trim - from end of text | |
} |
You don't need to escape those pesky dashes: https://gist.github.com/meowsus/e75867610b7d851baacf37567ce7c409/revisions
@hagemann could you please add an explicit license to this gist? :)
Wow! This is amazing. Thank you so much @hagemann!
Thank you so much!
It can support Turkish "İ" and "ı" characters with the lines below,
const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìıİłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;'
const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'
@melih I’ve added the 2 characters. Thanks for contributing.
Thank you so much.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
arabic