javascript 简单的javascript正则表达式来去除数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7847223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:32:32  来源:igfitidea点击:

Simple javascript regular expression to strip numbers

javascriptregex

提问by joedborg

All I want is to strip all the numbers from a string.

我想要的只是从字符串中去除所有数字。

So

所以

var foo = "bar01";
alert(foo.replace(/\d/,''));

Which obviously gives "bar1" because I've only specified one digit. So why doesn't this work:

这显然给出了“bar1”,因为我只指定了一个数字。那么为什么这不起作用:

var foo = "bar01";
alert(foo.replace(/\d*/,''));

Which gives "bar01"

这给出了“bar01”

回答by xanatos

You must add the globaloption

您必须添加global选项

var foo = "bar01";
alert(foo.replace(/\d/g,''));

Clearly you can even do something like

显然你甚至可以做类似的事情

var foo = "bar01";
alert(foo.replace(/\d+/g,''));

but I don't know if it will be faster (and in the end the difference of speed would be very very very small unless you are parsing megabytes of text)

但我不知道它是否会更快(最终速度的差异会非常非常非常小,除非您正在解析兆字节的文本)

If you want to test http://jsperf.com/replace-digitsthe second one seems to be faster for "blobs" of 10 digits and big texts.

如果您想测试http://jsperf.com/replace-digits,对于 10 位数字和大文本的“blob”,第二个似乎更快。

回答by duri

You probably want to specify the gflag: foo.replace(/\d/g,'')

您可能想要指定g标志:foo.replace(/\d/g,'')

回答by Prince John Wesley

alert(foo.replace(/\d+/g,''));

回答by Matthijs Bierman

Try the 'global' flag:

尝试“全局”标志:

foo.replace(/\d*/g,'')

foo.replace(/\d*/g,'')