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?
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.
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.
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.
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')
url = url.replace(/\//gi, " ");
Nothing changes because you're not assigning the result of the replacement to a variable. Add url = url.replace()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With