只保留AZ 0-9并使用javascript从字符串中删除其他字符

M.E*_*M.E 39 javascript string replace

我正在尝试验证字符串,使我们的有效网址

我需要保持AZ 0-9并使用javascriptjquery从字符串中删除其他字符

例如 :

Belle’s餐厅

我需要将其转换为:

百丽-S-餐厅

所以删除了字符,只保留了AZ az 0-9

谢谢

Sam*_*son 55

通过将我们的.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"
Run Code Online (Sandbox Code Playgroud)

因为正则表达式的末尾有一个加号,所以它匹配一个或多个字符.因此,'-'对于一个或多个非字母数字字符的每个系列,输出将始终具有一个:

# An example to demonstrate the effect of the plus sign in the regular expression above
var foo = "  Hello   World    . . .     ".cleanup(); // "-hello-world-"
Run Code Online (Sandbox Code Playgroud)

没有加号,结果将是"--hello-world--------------"最后一个例子.

  • 如果是小写,为什么是 AZ? (3认同)

Nic*_*lás 5

如果您想用破折号代替其他字符,则使用以下命令:

string.replace(/[^a-zA-Z0-9]/g,'-');
Run Code Online (Sandbox Code Playgroud)