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:

string.replace(orgStr,newStr);

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";  
  document.writeln(str.replace("world","world!"));  

Output:

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 laratutorials.com.";  
 document.writeln(str.replace(/Node/g,"javaScript"));  
 

Output:

Learn javaScript on laratutorials.com.

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 laratutorials.com. Node.js is a well-known JavaScript framework.";   document.writeln(str.replace(/Node.js/,"AngularJS")); //It will replace only first match.   

Output:

Learn AngularJS on laratutorials.com. 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 laratutorials.com.";  
document.writeln(str.replace(/Node.JS/gi,"AngularJS"));  

Output:

Learn AngularJS on laratutorials.com.

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');
console.log(result);

Output:

JavaScript will, JS will, JS will rock you!

Conclusion

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

Recommended JavaScript Tutorials

Leave a Comment