只保留A-Z 0-9并使用javascript从字符串中删除其他字符 [英] only keep A-Z 0-9 and remove other characters from string using javascript
问题描述
我正在尝试验证字符串以制作我们的有效网址
我只需保留AZ 0-9并使用从字符串中删除其他字符例如:
Belle’s餐厅
我需要将其转换为:
Belle -s-Restaurant
所以删除字符并保留AZ az 0-9
谢谢
添加我们的 .cleanup()
然后,您可以通过调用本地方法清理Javascript中的任何字符串,如下所示:
#将我们的方法附加到String对象
String.prototype.cleanup = function(){
返回this.toLowerCase()。replace(/ [^ a-zA-Z0-9] + / g, - );
}
#使用我们新的.cleanup()方法
var clean =Hello World.cleanup(); //你好世界
因为在正则表达式的末尾有一个加号它匹配一个或更多字符。因此,对于每个系列的一个或多个非字母数字字符,输出将始终具有一个' -
:
#一个示例,用于演示
var foo =Hello World ....cleanup();上方正则表达式中加号的效果。 //-hello-world-
如果没有加号,结果将是 - hello-world --------------
为最后一个例子。
i am trying to verify strings to make valid urls our of them
i need to only keep A-Z 0-9 and remove other characters from string using javascript or jquery
for example :
Belle’s Restaurant
i need to convert it to :
Belle-s-Restaurant
so characters ’s removed and only A-Z a-z 0-9 are kept
thanks
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:
# 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 more characters. 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.
这篇关于只保留A-Z 0-9并使用javascript从字符串中删除其他字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!