Skip to content

Instantly share code, notes, and snippets.

@shanelau
Created November 27, 2014 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shanelau/f56f4dde0892bc766a1d to your computer and use it in GitHub Desktop.
Save shanelau/f56f4dde0892bc766a1d to your computer and use it in GitHub Desktop.
安全字符串输出 中文转拼音
var unidecode = require('unidecode');
var safeString = function (string) {
string = string.trim();
// Remove non ascii characters
string = unidecode(string);
// Remove URL reserved chars: `:/?#[]@!$&'()*+,;=` as well as `\%<>|^~£"`
string = string.replace(/[:\/\?#\[\]@!$&'()*+,;=\\%<>\|\^~£"]/g, '')
// Replace dots and spaces with a dash
.replace(/(\s|\.)/g, '-')
// Convert 2 or more dashes into a single dash
.replace(/-+/g, '-')
// Make the whole thing lowercase
.toLowerCase();
console.log(string);
return string;
}
safeString('hello world');
safeString(' 我love天南门');
//hello-world
//wo-lovetian-nan-men-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment