views:

328

answers:

4

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.

+3  A: 

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

locationClean = location.replace(/\//g,' ');
Peter Bailey
+1  A: 

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

var loc =  location.host + location.pathname, // loc variable used for tesing
    locationArray = loc.split("/");
CMS
+2  A: 

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?

Guffa
A: 

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'

a6hi5h3k