Aviram Netanel Aviram Netanel - 8 months ago 47
Node.js Question

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 :

variableABC = 'A B C'

when I want it to be 'A D C'.


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