JavaScript Replace String

The JavaScript Replace function search for a specified string and replace the searched string with the newly specified string. The syntax of the string Replace in JavaScript is

String_Object.replace(String you want to change, Replacing_String)
  • String_Object to perform a search. Replace function will replace a portion of a string present in this String_Object.
  • String you want to change: Whatever you place here, Javascript string replace Function will replace it with a new string
  • Replacing_String: New string you want to insert into the String_Object.

JavaScript Replace String Example

This example will help you understand the String Replace function.

<!DOCTYPE html>
    <title> Replace in JavaScript </title>
    <h1> JavaScript Replace()</h1>
    var Str1 = "We are ABC working at abc company";
    var Str2 = "We are abc working at abc company";
    var Str3 = Str2.replace("abc","JavaScript");
    var Str4 = Str2.replace(/abc/g,"JavaScript");
    var Str5 = Str1.replace("abc","JavaScript");
    var Str6 = Str1.replace(/abc/gi,"JavaScript");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
JavaScript REPLACE Function

It finds substring ‘abc’ and substitute it with substring ‘JavaScript’ . If you observe the above screenshot, Although ‘abc’ substring is repeated twice in Str2, the Replace String Function is replacing the first occurrence

var Str3 = Str2.replace("abc","JavaScript");

In the next JavaScript line, we used a regular expression to search for the substring ‘abc’ globally. So, string Replace() function replace every occurrence of the word ‘abc’ with ‘JavaScript’

var Str4 = Str2.replace(/abc/g,"JavaScript");

Using regular expression gi to perform the case-insensitive search

var Str6 = Str1.replace(/abc/gi,"JavaScript");