Home > Blockchain >  How to remove specific letters using regex in javascript
How to remove specific letters using regex in javascript

Time:10-02

var cartstring = "27,00 - R"

How can I remove spaces and "-" and "R" using only regex (not allowed to use slice etc.)? 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 ",".

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.

CodePudding user response:

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)

CodePudding user response:

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)

  • Related