JavaScript Replace String Method

JavaScript string replace all occurrences of a character; Through this tutorial, i am going to show you how to replace all occurrences of a character from given string in javaScript using replace() method.

JavaScript String replace() Method

The JavaScript string replace() method is used to replace a part of a given string with a new sub-string. This method searches for specified regular expression in a given string and then replace it if the match occurs.

Syntax of JavaScript String replace() Method

The following syntax is represented replace() method:


Parameter of JS Replace() Method

  • orgStr– It represents the string to be searched and replaced.
  • newStr– It represents the new string that replaced with the searched string.

Example 1 – javaScript string replace substring in string

See the following example example to replace a substring.

  var str="hello world";  


hello world!

Example 2 – javaScript string replace with global search modifiers

To replace substring using regular expression with global search modifier.

  var str=" Learn Node on";  


Learn javaScript on

Example 3 – javaScript string replace without global search modifiers

To replace a regular expression without using a global search.

var str=" Learn Node.js on Node.js is a well-known JavaScript framework.";   document.writeln(str.replace(/Node.js/,"AngularJS")); //It will replace only first match.   


Learn AngularJS on Node.js is a well-known JavaScript framework

Example 4 – Replace with ignore case in javascript

You can ignore the case-sensitive behavior of replace() method by using the ignore flag modifier. Let’s understand with the help of an example:

var str=" Learn Node.js on";  


Learn AngularJS on

Example 5 – How to Replace All Occurrences of a Substring in a String

To replace all occurrences of a string in javascript; as shown below:

const message = 'JS will, JS will, JS will rock you!';
const result = message.replace('JS','JavaScript');


JavaScript will, JS will, JS will rock you!


In this tutorial, you have learned how to replace the string in javaScript using the replace() method.

Recommended JavaScript Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *