Does JavaScript have a method to replace part of a string without creating a new string?

JavascriptWeb DevelopmentObject Oriented Programming

Yes, we can replace part of a string without creating a new string using the replace() method as in the below syntax −

var anyVariableName=yourValue;
yourVariableName=yourVariableName.replace(yourOldValue,yourNewValue);

Example

var message="Hello,this is John";
console.log("Before replacing the message="+message);
message=message.replace("John","David Miller");
console.log("After replacing the message="+message);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo57.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo57.js
Before replacing the message=Hello,this is John
After replacing the message=Hello,this is David Miller
raja
Published on 03-Sep-2020 07:08:26
Advertisements