3

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.

2
  • Shit! I got it right after I asked... sorry everyone! Won't happen again... (hopefully). Commented Aug 14, 2009 at 21:12
  • 6
    Then answer your own question. Commented Aug 14, 2009 at 21:14

4 Answers 4

5

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

locationClean = location.replace(/\//g,' ');
Sign up to request clarification or add additional context in comments.

Comments

3

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?

Comments

2

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

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

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.