5

This seems so simple and trivial but it is not working. Here is my javascript:

var url = "/computers/";
console.log(url);
url.replace(/\//gi, " ");
console.log(url);

And here is the output in my browsers console:

/computers/
/computers/

As you can see nothing changes. As you can tell from the code I'm trying to replace the forward slashes with spaces. What am I doing wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
greatwitenorth
  • 2,241
  • 2
  • 19
  • 21

3 Answers3

21
url = url.replace(/\//gi, " ");
galchen
  • 5,252
  • 3
  • 29
  • 43
2

Nothing changes because you're not assigning the result of the replacement to a variable. Add url = url.replace()

dda
  • 6,030
  • 2
  • 25
  • 34
0

url.replace(/\//gi, " "); returns the resulting string (in javascript you can't modify an existing string), you are not assigning it to anything

assign it like so:

url = url.replace(/\//gi, " ");
Esailija
  • 138,174
  • 23
  • 272
  • 326