Javascript正则表达式,替换数字以外的所有字符 [英] Javascript regex, replace all characters other than numbers
本文介绍了Javascript正则表达式,替换数字以外的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Javascript替换字符串中除0-9以外的所有字符.
I would like to replace all the characters other than 0-9 in a string, using Javascript.
为什么此正则表达式不起作用?
Why would this regex not work ?
"a100.dfwe".replace(/([^0-9])+/i, "")
推荐答案
您需要使用/g
修饰符替换每次出现的情况:
You need the /g
modifier to replace every occurrence:
"a100.dfwe".replace(/[^0-9]+/g, "");
我还为您删除了多余的 i
修饰符和未使用的捕获子表达式大括号.正如其他人指出的那样,您还可以使用 \ D
来进一步缩短它:
I also removed the redundant i
modifier and the unused capturing sub-expression braces for you. As others have pointed out, you can also use \D
to shorten it even further:
"a100.dfwe".replace(/\D+/g, "");
这篇关于Javascript正则表达式,替换数字以外的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文