簡體   English   中英

簡單的javascript正則表達式來刪除數字

[英]Simple javascript regular expression to strip numbers

我想要的是從字符串中刪除所有數字。

所以

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

這顯然給了“bar1”因為我只指定了一個數字。 那么為什么這不起作用:

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

哪個給“bar01”

您必須添加global選項

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

顯然,你甚至可以做類似的事情

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

但我不知道它是否會更快(最后速度的差異將非常小,除非你解析兆字節的文本)

如果你想測試http://jsperf.com/replace-digits ,那么對於10位數字和大文本的“blob”來說,第二個似乎更快。

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

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

試試'全球'標志:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM