0

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.

5
  • 1
    what is your expected output? Commented Oct 1, 2021 at 15:19
  • 3
    Why not some kind of cartstring.split(" ")[0]? Commented Oct 1, 2021 at 15:19
  • @SamridhTuladhar "27,00" on both Commented Oct 1, 2021 at 15:20
  • 1
    You could also remove any char except digits or a comma [^\d,]+regex101.com/r/OcQvSP/1 Commented Oct 1, 2021 at 15:21
  • as The fourth bird said, use text.replace(/[^0-9,]/g, '') Commented Oct 1, 2021 at 15:30

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks all, that was very informative.
1

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)

Comments

0

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.

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:

var cartstring = "27,00 - R";
console.log(cartstring.replace(/[^\d,]+/g, ''));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.