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

B.Wesselink
  • 63
  • 12
  • 1
    Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript). – Álvaro González Sep 14 '16 at 12:10
  • [*"The `replace()` method **returns a new string** with some or all matches of a pattern replaced by a replacement."*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) – epascarello Sep 14 '16 at 12:14

2 Answers2

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);
Community
  • 1
  • 1
osjo
  • 131
  • 6
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);
pachonjcl
  • 723
  • 4
  • 11
  • Hmm, it worked, why didnt Rajesh option worked? And why does it work like you say? What does the "regex" do? – B.Wesselink Sep 14 '16 at 12:19
  • 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](http://www.w3schools.com/jsref/jsref_obj_regexp.asp) – pachonjcl Sep 14 '16 at 12:25