Created
January 2, 2021 01:29
-
-
Save ThienTranDuy/23b94770766f307a25cba2f23ed00f09 to your computer and use it in GitHub Desktop.
JS - convert string to slug URL - Unicode
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
/* | |
* convert from https://freetuts.net/tao-slug-tu-dong-bang-javascript-va-php-199.html | |
* @param string str | |
* @return string | |
*/ | |
const convertToSlug = function(str) { | |
let title, slug | |
//Đổi chữ hoa thành chữ thường | |
slug = str.toLowerCase() | |
//Đổi ký tự có dấu thành không dấu | |
slug = slug.replace(/á|à|ả|ạ|ã|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ/gi, 'a') | |
slug = slug.replace(/é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ/gi, 'e') | |
slug = slug.replace(/i|í|ì|ỉ|ĩ|ị/gi, 'i') | |
slug = slug.replace(/ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ/gi, 'o') | |
slug = slug.replace(/ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự/gi, 'u') | |
slug = slug.replace(/ý|ỳ|ỷ|ỹ|ỵ/gi, 'y') | |
slug = slug.replace(/đ/gi, 'd') | |
//Xóa các ký tự đặt biệt | |
slug = slug.replace(/\`|\~|\!|\@|\#|\||\$|\%|\^|\&|\*|\(|\)|\+|\=|\,|\.|\/|\?|\>|\<|\'|\"|\:|\|_/gi, '') | |
//Đổi khoảng trắng thành ký tự gạch ngang | |
slug = slug.replace(/ /gi, "-") | |
//Đổi nhiều ký tự gạch ngang liên tiếp thành 1 ký tự gạch ngang | |
//Phòng trường hợp người nhập vào quá nhiều ký tự trắng | |
slug = slug.replace(/\-\-\-\-\-/gi, '-') | |
slug = slug.replace(/\-\-\-\-/gi, '-') | |
slug = slug.replace(/\-\-\-/gi, '-') | |
slug = slug.replace(/\-\-/gi, '-') | |
//Xóa các ký tự gạch ngang ở đầu và cuối | |
slug = '@' + slug + '@' | |
slug = slug.replace(/\@\-|\-\@|\@/gi, '') | |
//In slug ra textbox có id “slug” | |
return slug | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment