Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...

I have this:

var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');

locationArray = locationClean.split(" ");

console.log(location);
console.log(locationClean);
console.log(locationArray);

And here is what I am getting in Firebug:

stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]

So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).

Thanks all.

like image 927
Ian Storm Taylor Avatar asked May 14 '26 04:05

Ian Storm Taylor


2 Answers

Use a pattern instead of a string, which you can use with the "global" modifier

locationClean = location.replace(/\//g,' ');
like image 66
Peter Bailey Avatar answered May 16 '26 17:05

Peter Bailey


The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:

locationClean = location.replace(/\//g,' ');

(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)

Still, why are you not just splitting on the '/' character instead?

like image 32
Guffa Avatar answered May 16 '26 16:05

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!