-1

I have these strings with numbers

"$12.3"
"12,3 SEK"
"12 pounds"

In all the occurrences i need to remove the number, float or not, and just keep the rest of the string.

"$"
"SEK"
"pounds"

I found several posts that are similar to my question, like this one: Removing Numbers from a String using Javascript

Where something like this is suggested in a comment:

"12.3 USD".replace(/\d+([,.]\d+)?/g)

But that only returns (with the Chrome dev console):

"undefined USD"
3
  • str = str.replace(/\d*[,.]?\d+[ \t]*/g, ''); Commented Oct 18, 2017 at 20:12
  • A simple lookup of the method replace() would have shown you it takes 2 arguments Commented Oct 18, 2017 at 20:16
  • The problem is, you have no idea what part of non-digits adjacent to numbers are actually part of the number. For example %.7 Commented Oct 18, 2017 at 20:48

1 Answer 1

7

That's because you aren't telling it what to replace those values with. Try

"12.3 USD".replace(/\d+([,.]\d+)?/g, '')
//   replace with an empty string ---^

It looks like you also want to remove any whitespace coming after the numbers so you could modify your regex a bit to do that.

let result = "12.3 USD".replace(/\d+([,.]\d+)?\s*/g, '');
//                       remove whitespace ---^
console.log(result);

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

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.