Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Javascript Replace not working [duplicate]

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?

like image 440
greatwitenorth Avatar asked Jun 02 '12 14:06

greatwitenorth


People also ask

Why replace is not working in Javascript?

The "replace is not a function" error occurs when we call the replace() method on a value that is not of type string . To solve the error, convert the value to a string using the toString() method before calling the replace() method. Here is an example of how the error occurs.

Does replace replace all occurrences?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

What is replace () in Javascript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

What can I use instead of replaceAll in Javascript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')


2 Answers

url = url.replace(/\//gi, " ");
like image 65
galchen Avatar answered Sep 22 '22 10:09

galchen


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

like image 28
dda Avatar answered Sep 24 '22 10:09

dda