[英]How to remove specific letters using regex in javascript
var cartstring = "27,00 - R"
How can I remove spaces and "-" and "R" using only regex (not allowed to use slice etc.)?如何仅使用正则表达式(不允许使用 slice 等)删除空格和“-”和“R”? I need to make strings cartstring1 and cartstring2 which should both be equal to "27,00", first by removing spaces and "-" and "R", and second by allowing only numbers and ",".
我需要创建都应等于“27,00”的字符串 cartstring1 和 cartstring2,首先删除空格和“-”和“R”,然后只允许使用数字和“,”。
cartstring1 = cartstring.replace(/\s/g, "");
cartstring2 = cartstring.replace(/\D/g, "");
Please help me modify these regular expressions to have a working code.请帮助我修改这些正则表达式以获得有效代码。 I tried to read about regex but still cannot quite get it.
我试图阅读有关正则表达式的内容,但仍然不太明白。
Thank you very much in advance.非常感谢你提前。
you can just capture just what you are interested in number and comma:您可以只捕获您对数字和逗号感兴趣的内容:
let re = /[\d,]+/g let result = "27,00 - R".match(re) console.log(result)
You can group the characters you want to remove:您可以对要删除的字符进行分组:
var cartstring = "27,00 - R" let res = cartstring.replace(/(\s|-|R)/g, "") console.log(res)
Or alternatively, split the string by a space and get the first item:或者,用空格分隔字符串并获取第一项:
var cartstring = "27,00 - R" let res = cartstring.split(" ")[0] console.log(res)
You are using 2 replacements, one replacing all whitespace chars \s
and the other replacing all non digits \D
, but note that \D
also matches \s
so you could omit the first call.您正在使用 2 个替换,一个替换所有空白字符
\s
,另一个替换所有非数字\D
,但请注意\D
也与\s
匹配,因此您可以省略第一个调用。
Using \D
will also remove the comma that you want to keep, so you can match all chars except digits or a comma using [^\d,]+
in a single replacement instead:使用
\D
还将删除您想要保留的逗号,因此您可以在单个替换中使用[^\d,]+
匹配除数字或逗号以外的所有字符:
var cartstring = "27,00 - R"; console.log(cartstring.replace(/[^\d,]+/g, ''));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.