0

I was trying to run this line of code and wondering why it is not working. Does anyone has an answer for this?

var string = "foo     bar";
string = string.replace(" ", "");
alert(string.length);

why issit that the length of the string is not changed to 6 instead?

4 Answers 4

4

The function only replaces one instance of the string you search for.

To replace more, you can match with a regular expression:

string = string.replace(/\s+/g, '');

That strips all "whitespace" characters. The "\s" matches whitespace, the "+" means "one or more occurrences" of whitespace characters, and the trailing "g" means "do it to all matching sequences in the string".

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

Comments

2

Because you have more than one space in your string and the .replace is replacing one space, the first one encountered.

This works as expected, with only one space

var string = "foo bar";
string = string.replace(" ", "");
alert(string.length);

Comments

1

replace, when passed a string as the first parameter, only replaces the first occurrence of that string. To replace everything, you'd need a regular expression:

alert("foo     bar".replace(/ /g, ""));

Comments

0

That's because only one space has been replaced. Per JavaScript 1.5 specification, String.replace() takes a regular expression as first parameter and the behavior for string parameters is undefined. Browsers later decided to treat strings similarly - but there is no way to specify g flag on a string, so only one replacement is done. This will do what you want:

string = string.replace(/ /g, '');

The version provided by Pointy (/\s+/g) might be more efficient however. And it will replace other types of whitespace (tabs, newlines) as well.

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.