Simple Javascript Replace not working

2019-01-27 23:49发布

问题:

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?

回答1:

url = url.replace(/\//gi, " ");


回答2:

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



回答3:

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, " ");