I would like to remove all special characters (except for numbers) from a string. I have been able to get this far
我想从字符串中删除所有特殊字符(除了数字)。我能走到这一步
var name = name.replace(/[^a-zA-Z ]/, "");
but it seems that it is removing the first number and leaving all of the others.
但它似乎去掉了第一个数字,剩下所有其他的数字。
For example:
例如:
name = "collection1234"; //=> collection234
or
或
name = "1234567"; //=> 234567
3 个解决方案
#1
27
Use the global flag:
使用全球标志:
var name = name.replace(/[^a-zA-Z ]/g, "");
^
If you don't want to remove numbers, add it to the class:
如果您不想删除数字,请将其添加到类中:
var name = name.replace(/[^a-zA-Z0-9 ]/g, "");
#2
13
To remove the special characters, try
要删除特殊字符,请尝试
var name = name.replace(/[!@#$%^&*]/g, "");
#3
5
If you don't mind including the underscore as an allowed character, you could try simply:
如果您不介意将下划线包含为允许字符,您可以尝试:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
如果下划线也必须排除,那么。
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
(注意不区分大小写的标志)
#1
27
Use the global flag:
使用全球标志:
var name = name.replace(/[^a-zA-Z ]/g, "");
^
If you don't want to remove numbers, add it to the class:
如果您不想删除数字,请将其添加到类中:
var name = name.replace(/[^a-zA-Z0-9 ]/g, "");
#2
13
To remove the special characters, try
要删除特殊字符,请尝试
var name = name.replace(/[!@#$%^&*]/g, "");
#3
5
If you don't mind including the underscore as an allowed character, you could try simply:
如果您不介意将下划线包含为允许字符,您可以尝试:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
如果下划线也必须排除,那么。
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
(注意不区分大小写的标志)