In Javascript, you can use the replace() method to replace the string. This method allows to pass two parameters in it. The first parameter is the string that you want to replace, on the other hand, the second parameter will be the new substring on the replacement of the first string parameter.

Replace method allows you to replace occurrences of a specific substring with a new substring. This method is generally helpful when you are transforming content.

Knowing how to use the replace() function in JavaScript is useful because it allows you to easily manipulate and work with strings. Here’s how you can do it:

How to use Replace() method:

Replace a Single Occurrence:

In the example below, the replace() method replaces all occurrences of the substringToReplace (“Hello”) in the originalString with the newSubstring (“Hi”), resulting in the updatedString.

Replace All Occurrences using Regular Expression:

If you want to replace all occurrences of the substring globally, you can use a regular expression with the /g flag:

Learn more: [11] Helpful Functions in Javascript that You Need to Know

Replacing Case-Insensitive Occurrences:

The above one is case-sensitive, so if you want irrespective of the letter case then use /gi flag:

Using a Function as the Replacement:

Replacing with Different Substrings:


🗒️ Note: Remember that the replace() method returns a new string with the replacements made. It doesn’t modify the original string.

So, that’s all about replace substring in javascript. I hope you enjoyed the article and if you found this useful, then please share it with your friends and colleagues.

If you have any queries please feel free to post them in the comments section or anything that you wanted to ask through mail contact.

Happy Coding!.

Also read,