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
  • 698,132
  • 130
  • 858
  • 1,229
greatwitenorth
  • 2,006
  • 2
  • 18
  • 21

3 Answers3

21
url = url.replace(/\//gi, " ");
galchen
  • 5,212
  • 3
  • 27
  • 42
2

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

dda
  • 5,760
  • 2
  • 24
  • 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
  • 134,577
  • 23
  • 263
  • 318