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 Answers 2
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);
2 Comments
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 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
URL = URL.replace(/-/g,"/");
replace()method returns a new string with some or all matches of a pattern replaced by a replacement."