JavaScript - String replaceAll() Method

In this post, we will discuss about replaceAll() method in JavaScript. replaceAll() is a method of string used to replace all occurrence of matching value.

Let us create the String for demonstration.

CopiedCopy Code
let string1='student who gets first marks that student will be eligible for scholarship';
console.log(string1);

Output:

student who gets first marks that student will be eligible for scholarship

String replaceAll():

replaceAll() used to replace all the occurrences of the matching with the given string.

replaceAll() syntax:

String.replaceAll('findValue','replaceValue')

Where 'findValue' is used to find the string contains if it found replaces with 'replaceValue' for all occurrences. And it is not going to change the original value of the string but it returns new string with changes. We will see how to replace the string with the given string in the examples.

replaceAll() example 1:

create a string declaration with sentence and replace any part of the sentence with new string.

CopiedCopy Code
let string1='student who gets first marks that student will be eligible for scholarship';
console.log('Given String = '+string1);
let newreplacestring = string1.replaceAll('student','scholar');
console.log('New String with replace all = '+newreplacestring);

Execution Steps:

  1. Copy the above example code.
  2. Open the browser(chrome or Microsoft edge) and press(ctrl+shift+I).
  3. Go to the console tab.
  4. Paste the code into console and press enter button.

Output:

Given String = student who gets first marks that student will be eligible for scholarship

New String with replace all = scholar who gets first marks that scholar will be eligible for scholarship