questions on javascript - string.replace()
I开发者_如何学JAVA 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?
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".
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);
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, ""));
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.
精彩评论