0

I am having some issues with the simple .replace() function from JS.

Here is my code

    console.log(URL);
    URL.replace("-","/");
    console.log(URL);

Here is my output:

folder1-folder2-folder3 folder1-folder2-folder3

the second one should be

folder1/folder2/folder3

right?

If you guys need from my code, please let me know :)

Thanks in advance,

Bram

2

2 Answers 2

3

The correct thing is to replace it with a global regex with g after the regex that in this case is /-/

console.log(URL);
URL = URL.replace(/-/g,"/");
console.log(URL);
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, it worked, why didnt Rajesh option worked? And why does it work like you say? What does the "regex" do?
regex is a regular expression that matchs patterns and with string replace method you can replace any ocurrence with something that you want, g regex modifier is to match all the ocurrence while normally would replace only the first one Check this
3

Replace returns a new string after replacement. It does not alter the string that replace was called on. Try this:

console.log(URL);
URL = URL.replace("-","/");
console.log(URL);

To replace all occurences look at this How to replace all occurrences of a string in JavaScript?

console.log(URL);
URL = URL.replace(/-/g, '/');
console.log(URL);

3 Comments

Some progress, but now I get: folder1/folder2-folder3
@B.Wesselink you will have to use regex. URL = URL.replace(/-/g,"/");
Now I get an "undefined"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.