Skip to content

Instantly share code, notes, and snippets.

@laocoi
Last active March 29, 2024 04:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save laocoi/45ce064205b2b97b2548476c4bae9d88 to your computer and use it in GitHub Desktop.
Save laocoi/45ce064205b2b97b2548476c4bae9d88 to your computer and use it in GitHub Desktop.
Create Vietnamese slug from string - Javascript
function slugify(string){
const a = 'àáäâãåăæąçćčđďèéěėëêęğǵḧìíïîįłḿǹńňñòóöôœøṕŕřßşśšșťțùúüûǘůűūųẃẍÿýźžż·/_,:;'
const b = 'aaaaaaaaacccddeeeeeeegghiiiiilmnnnnooooooprrsssssttuuuuuuuuuwxyyzzz------'
const p = new RegExp(a.split('').join('|'), 'g')
return string.toString().toLowerCase()
.replace(/á|à|ả|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/gi, 'a')
.replace(/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ/gi, 'e')
.replace(/i|í|ì|ỉ|ĩ|ị/gi, 'i')
.replace(/ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ/gi, 'o')
.replace(/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/gi, 'u')
.replace(/ý|ỳ|ỷ|ỹ|ỵ/gi, 'y')
.replace(/đ/gi, 'd')
.replace(/\s+/g, '-')
.replace(p, c => b.charAt(a.indexOf(c)))
.replace(/&/g, '-and-')
.replace(/[^\w\-]+/g, '')
.replace(/\-\-+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
}
@le-huy-jh
Copy link

Thanks

@fuzz-dev
Copy link

Useful

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