How to replace multiple lines with replace () in Javascript

I assume this is a simple problem, but I'm just studying ...

I have it:

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 get 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 replacement occurs only once? Do I need to use Regex instead of "/ g" to repeat it? And if so, how would I specify "/" in Regex? (I understand very little how to use Regex).

Thanks to everyone.

+3
source share
4 answers

The replace method replaces only the first occurrence when you use a string as the first parameter. You should use regex to replace all events:

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

( , .)

, '/' ?

+3

, ""

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

split / :

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

javascript.

stringObject.replace(findstring,newstring)

findstring: . . , "g" , "i".

newstring: . findstring

shud:

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

njoi

0

Source: https://habr.com/ru/post/1715206/


All Articles