up vote 0 down vote favorite
1

Hey Guys,

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.

link|flag

Shit! I got it right after I asked... sorry everyone! Won't happen again... (hopefully). – Ian Storm Taylor Aug 14 '09 at 21:12
6  
Then answer your own question. – jason Aug 14 '09 at 21:14

4 Answers

up vote 2 down vote accepted

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?

link|flag
up vote 3 down vote

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

locationClean = location.replace(/\//g,' ');
link|flag
up vote 1 down vote

You could directly split using the / character as the separator:

var loc =  location.host + location.pathname, // loc variable used for tesing
    locationArray = loc.split("/");
link|flag
up vote 0 down vote

This can be fixed from your javascript.

SYNTAX

stringObject.replace(findstring,newstring)

findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.

newstring: Required. Specifies the string to replace the found value from findstring

Here's what ur code shud look like:

locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");

njoi'

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.