questions on javascript - string.replace()

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?

Answers


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.


Need Your Help

SL media element won't play my wave file after the first time

silverlight wav mediaelement wavmss

I use WaveMediaStreamSource (WAVmss) library to play wave files on silverlight media element.

Using ToString() in LINQ queries?

c# asp.net linq-to-entities entity-framework-5

I have writting a LINQ query to fill a listview but it useses the .ToString() method which apparetly is not allowed. When I use the below code I get the error message:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.