我正在尝试验证字符串以使它们成为我们的有效 url
我只需要保留 A-Z 0-9 并使用 javascript 或 jquery 从字符串中删除其他字符
例如:
百丽餐厅
我需要将其转换为:
Belle-s-Restaurant
所以字符被删除,只保留 A-Z a-z 0-9
谢谢
最佳答案
通过将我们的 .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"
因为正则表达式末尾有一个加号,所以它匹配一个或多个字符。因此,对于一个或多个非字母数字字符的每个系列,输出总是有一个 '-'
:
# An example to demonstrate the effect of the plus sign in the regular expression above
var foo = " Hello World . . . ".cleanup(); // "-hello-world-"
如果没有加号,最后一个示例的结果将是 "--hello-world------------"
。
关于javascript - 只保留 A-Z 0-9 并使用 javascript 从字符串中删除其他字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1983767/