How to fix string.replace doesn’t change the variable with JavaScript?

Sometimes, we want to fix string.replace doesn’t change the variable with JavaScript.

In this article, we’ll look at how to fix string.replace doesn’t change the variable with JavaScript.

How to fix string.replace doesn’t change the variable with JavaScript?

To fix string.replace doesn’t change the variable with JavaScript, we assign the returned string to a new variable.

For instance, we write

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

to call variableABC.replace with the regex and 'D' to replace all B’s with D’s and return the string with the replacements.

Then we assign the returned value back to variableABC to update it.

Conclusion

To fix string.replace doesn’t change the variable with JavaScript, we assign the returned string to a new variable.