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"
.
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.
You could use simple regex: var result = fileAsString. replace(/string to be replaced/g, 'replacement');
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.
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");
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'
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