只保留 AZ 0-9 并使用 javascript 从字符串中删除其他字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1983767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
only keep A-Z 0-9 and remove other characters from string using javascript
提问by M.E
i am trying to verify strings to make valid urls our of them
我正在尝试验证字符串以使有效的 url 成为我们的
i need to only keep A-Z 0-9 and remove other characters from string using javascriptor jquery
我只需要保留 AZ 0-9 并使用javascript或jquery从字符串中删除其他字符
for example :
例如 :
Bellea?s Restaurant
贝利亚餐厅
i need to convert it to :
我需要将其转换为:
Belle-s-Restaurant
百丽餐厅
so characters a?s removed and only A-Z a-z 0-9 are kept
所以字符 a?s 被删除,只有 AZ az 0-9 被保留
thanks
谢谢
回答by Sampson
By adding our .cleanup()method to the String object itself, you can then cleanup any string in Javascript simply by calling a local method, like this:
通过将我们的.cleanup()方法添加到 String 对象本身,您可以简单地通过调用本地方法来清除 Javascript 中的任何字符串,如下所示:
# Attaching our method to the String Object
String.prototype.cleanup = function() {
return this.toLowerCase().replace(/[^a-zA-Z0-9]+/g, "-");
}
# Using our new .cleanup() method
var clean = "Hello World".cleanup(); // "hello-world"
Because there is a plus sign at the end of the regular expression it matches one or morecharacters. Thus, the output will always have one '-'for each series of one or more non-alphanumeric characters:
因为正则表达式末尾有一个加号,它匹配一个或多个字符。因此,'-'对于每一系列的一个或多个非字母数字字符,输出将始终有一个:
# An example to demonstrate the effect of the plus sign in the regular expression above
var foo = " Hello World . . . ".cleanup(); // "-hello-world-"
Without the plus sign the result would be "--hello-world--------------"for the last example.
如果没有加号,结果将是"--hello-world--------------"最后一个示例。
回答by Nicolás
Or this if you wanted to put dashes in the place of other chars:
或者,如果您想将破折号放在其他字符的位置:
string.replace(/[^a-zA-Z0-9]/g,'-');
回答by TodPunk
Assuming that the string is kept in a variable called BizName:
假设字符串保存在一个名为 的变量中BizName:
BizName.replace(/[^a-zA-Z0-9]/g, '-');
BizNameshould now only involve the characters requested.
BizName现在应该只涉及请求的字符。

