Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js string.replace doesn't work?

var variableABC = "A B C";  variableABC.replace("B", "D") // Wanted output: "A D C". 

but variableABC didn’t change:

console.log(variableABC); // "A B C" 

I want it to be "A D C".

like image 455
Aviram Netanel Avatar asked Jan 16 '14 12:01

Aviram Netanel


People also ask

Why string 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.

How do you replace a word in node?

You could use simple regex: var result = fileAsString. replace(/string to be replaced/g, 'replacement');

Does string replace replacing all occurrences?

The String type provides you with the replace() and replaceAll() methods that allow you to replace all occurrences of a substring in a string and return the new version of the string.


2 Answers

According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

You can always just set the string to the modified value:

variableABC = variableABC.replace('B', 'D')

Edit: The code given above is to only replace the first occurrence.

To replace all occurrences, you could do:

 variableABC = variableABC.replace(/B/g, "D");   

To replace all occurrences and ignore casing

 variableABC = variableABC.replace(/B/gi, "D");   
like image 83
Munim Avatar answered Sep 18 '22 08:09

Munim


Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";  variableABC = variableABC.replace('B', 'D') //output: 'A D C' 
like image 38
Jon Avatar answered Sep 19 '22 08:09

Jon