正则表达式不会从字符串中删除非数字

时间:2022-07-15 16:52:04

I have the following string "item number:237728" I'm applying replace

我有以下字符串“项目编号:237728”我正在申请替换

str.replace(/[^0-9]/g,'');

but the string does not change, non digits are not removed. any idea why? thanks

但字符串不会更改,不会删除非数字。知道为什么吗?谢谢

2 个解决方案

#1


Are you assigning the returned value and using that, e.g. str = str.replace(/[^0-9]/g,'');, or expecting the original string to change?

您是否正在分配返回的值并使用它,例如str = str.replace(/ [^ 0-9] / g,'');或者期望原始字符串改变?

String functions don't modify the original string, they return the modified strings.

字符串函数不修改原始字符串,它们返回修改后的字符串。

#2


This worked, try pasting into the location box of your browser:

这很有效,尝试粘贴到浏览器的位置框中:

javascript:alert("item number:237728".replace(/[^0-9]/g,""))

As Neal says, I suspect your problem might be that of string mutability. Make sure you catch the return value from replace().

正如尼尔所说,我怀疑你的问题可能是字符串可变性。确保从replace()中捕获返回值。

#1


Are you assigning the returned value and using that, e.g. str = str.replace(/[^0-9]/g,'');, or expecting the original string to change?

您是否正在分配返回的值并使用它,例如str = str.replace(/ [^ 0-9] / g,'');或者期望原始字符串改变?

String functions don't modify the original string, they return the modified strings.

字符串函数不修改原始字符串,它们返回修改后的字符串。

#2


This worked, try pasting into the location box of your browser:

这很有效,尝试粘贴到浏览器的位置框中:

javascript:alert("item number:237728".replace(/[^0-9]/g,""))

As Neal says, I suspect your problem might be that of string mutability. Make sure you catch the return value from replace().

正如尼尔所说,我怀疑你的问题可能是字符串可变性。确保从replace()中捕获返回值。