1

I cannot remove a whitespace in a string if a variable contains that value:

var groupingSeparator = ' '; '123 456'.replace( new RegExp( groupingSeparator ), '' ); >>> as result: '123 456' 

But I can do it without a separate variable:

'123 456'.replace( new RegExp( ' ' ), '' ); >>> as result: '123456' 

I need this variable because it could also contain another value (comma, point and go on). So why we have a different behavior in the "equals" code examples? How to solve it?

EDIT: So it does not work for me locally because the value of the groupSeparator variable is not a simple whitespace. It is '\u00A0'.

4
  • 1
    '123 456'.replace( new RegExp( groupingSeparator ), '' ); yields 123456 Commented Dec 3, 2018 at 11:49
  • @WiktorStribiżew You are right. Maybe it is an issue with my local code... Commented Dec 3, 2018 at 11:51
  • Don't forget to assign the replaced value: str = str.replace( new RegExp( g ), '' ); Commented Dec 3, 2018 at 11:53
  • So it does not work for me locally because the value of the groupSeparator variable is not simple whitespace. It is '\u00A0'. Commented Dec 3, 2018 at 12:13

1 Answer 1

1

Use \s as separator - it matches whitespaces. Note that you need to add "\" to use it with RegExp constructor. I've also added g flag (global) to replace all matches in given string

var groupingSeparator = '\\s'; var text = '123\u00a0456' console.log("before", text) var result = text.replace( new RegExp( groupingSeparator , "g"), '' ); console.log("after", result)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.