-1

I have a problem to find a regular expression to replace all spaces in given string:

var test = '1 2 3 4';
alert(test.replace(/\s/, ''));

The first space is replaced correctly but I want to get the string without any spaces. In the example above I'm expecting "1234".

altralaser
  • 2,035
  • 5
  • 36
  • 55

2 Answers2

1

You have to add a g flag for global at the end of your Regular Expression:

var test = '1 2 3 4';
alert(test.replace(/\s/g, ''));

Look at 'flags' on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

putvande
  • 15,068
  • 3
  • 34
  • 50
0
alert(test.replace(/\s/g, ''));

"g" for "global"

user2196728
  • 2,915
  • 3
  • 16
  • 15