我想从字符串中删除所有特殊字符和空格,并用下划线替换.字符串是
var str = "hello world & hello universe";
Run Code Online (Sandbox Code Playgroud)
我现在有这个只替换空格:
str.replace(/\s/g, "_");
Run Code Online (Sandbox Code Playgroud)
我得到的结果是hello_world_&_hello_universe,但我想删除特殊符号.
我试过这个,str.replace(/[^a-zA-Z0-9]\s/g, "_")但这没有用.
epa*_*llo 88
您的正则表达式[^a-zA-Z0-9]\s/g表示匹配任何不是数字或字母后跟空格的字符.
删除\ s,如果你想要每个特殊字符的_,你应该得到你想要的东西.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
Run Code Online (Sandbox Code Playgroud)
这将导致 hello_world___hello_universe
如果您希望它是单个下划线,请使用+来匹配多个
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
Run Code Online (Sandbox Code Playgroud)
这将导致 hello_world_hello_universe
从新的正则表达式中删除\s,它应该可以工作 - 空格已经包含在“除字母数字之外的任何内容”中。
请注意,您可能需要+在 后面添加],这样您就不会得到超过一个下划线的序列。您还可以链接到.replace(/^_+|_+$/g,'')字符串的开头或结尾处修剪下划线。
并没有精确地要求删除重音(仅特殊字符),但我需要这样做。
此处给出的解决方案有效,但它们不会删除重音:é、è 等。
因此,在执行 epascarello 的解决方案之前,您还可以执行以下操作:
var newString = "développeur & intégrateur";
newString = replaceAccents(newString);
newString = newString.replace(/[^A-Z0-9]+/ig, "_");
alert(newString);
/**
* Replaces all accented chars with regular ones
*/
function replaceAccents(str) {
// Verifies if the String has accents and replace them
if (str.search(/[\xC0-\xFF]/g) > -1) {
str = str
.replace(/[\xC0-\xC5]/g, "A")
.replace(/[\xC6]/g, "AE")
.replace(/[\xC7]/g, "C")
.replace(/[\xC8-\xCB]/g, "E")
.replace(/[\xCC-\xCF]/g, "I")
.replace(/[\xD0]/g, "D")
.replace(/[\xD1]/g, "N")
.replace(/[\xD2-\xD6\xD8]/g, "O")
.replace(/[\xD9-\xDC]/g, "U")
.replace(/[\xDD]/g, "Y")
.replace(/[\xDE]/g, "P")
.replace(/[\xE0-\xE5]/g, "a")
.replace(/[\xE6]/g, "ae")
.replace(/[\xE7]/g, "c")
.replace(/[\xE8-\xEB]/g, "e")
.replace(/[\xEC-\xEF]/g, "i")
.replace(/[\xF1]/g, "n")
.replace(/[\xF2-\xF6\xF8]/g, "o")
.replace(/[\xF9-\xFC]/g, "u")
.replace(/[\xFE]/g, "p")
.replace(/[\xFD\xFF]/g, "y");
}
return str;
}Run Code Online (Sandbox Code Playgroud)
来源:https : //gist.github.com/jonlabelle/5375315
| 归档时间: |
|
| 查看次数: |
78890 次 |
| 最近记录: |