JavaScript replace Method

Visual representation of the JavaScript replace function.

What is the string replace method of JavaScript?

The JavaScript replace method is used to find and replace a given term in a string.

For example:

var source_string = “The is a JavaScript tutorial”;

var rep_string = source_string.replace(“JavaScript”,”JS”);

See the examples in the coming section for using the replace JS method with simple as well as regular expressions.

Syntax of JavaScript replace

string.replace(searchValue, newValue)

Where:

Parameter/return value Description
searchValue
  • You have to provide the searchValue to be replaced in the specified string.
  • It can be a string or a regular expression representing the pattern to be replaced.
newValue
  • The newValue is also required.
  • It is a substring that replaces the matched pattern.
return value The return string after using the replace method is a modified string replaced with a given term (if found).

A simple example to replace string

In this example, I have created a string and assigned it to a JS variable. The string is:

“A JavaScript tutorial with demo”

After that, the JS replace method is used where “JavaScript” is replaced by the word “JS”.

The variable’s value after using the replace method is displayed in a div element as the page loads.

JavaScript and HTML:

<!DOCTYPE html>
<html>
<head>
<style>
.divclass {
  background: #038D98;
  height: auto;
  width:350px;
  border-radius: 15px;
  padding:20px;
  font-size:16px;
  color:#fff;  
}
#repstring {
    background: #FA4238;
}
</style>
</head>

<body>
<div class="divclass"><p><strong>Source string:</strong> A JavaScript tutorial with demo</p> 
<p><strong>Executing replace method: </strong> </p><p style="background-color: green;"> var str_rep = src_str.replace("JavaScript","JS");</p>
<p><strong>After replace method:  </strong><span id="repstring"></span></p>

<script type="text/javascript">
var src_str = ("A JavaScript tutorial with demo");
var str_rep = src_str.replace("JavaScript","JS");

document.getElementById("repstring").innerHTML = str_rep;

</script>
</body>
</html>

 

JavaScript replace

See the following code in <script> section, where the replace method is used:

<script type="text/javascript">

var src_str = ("A JavaScript tutorial with demo");

var str_rep = src_str.replace("JavaScript","JS");

document.getElementById("repstring").innerHTML = str_rep;

</script>

The last line displays the value of the “replaced” string in the <span> tag which is inside the main div.

Also, note that the replace method is case-sensitive. If the word “javascript” was used in the replace method, the source string would have remained the same.

An example is shown in the later part of this tutorial to perform the case-insensitive replacement.

A demo of replace method to replace all matched words in a string

By default, the replace method changes the first occurrence of the matched string.

Even if the source string has multiple occurrences, it will still replace just the first occurrence. See this example where the word “test” is replaced by “TEST”.

The code:

<!DOCTYPE html>
<html>
<head>
<style>
.divclass {
  background: #038D98;
  height: auto;
  width:350px;
  border-radius: 15px;
  padding:20px;
  font-size:16px;
  color:#fff;  
}
span {
    background: #FA4238;
}
.btncls{
    background-color:#F6B33C;
    border: #2e6da4;
  	font-family: Arial, Geneva, Arial, Helvetica,  sans-serif;
	font-size: 15px;
    color: #FFFFFF;
    letter-spacing: 1px;
    padding: 8px 12px;
    font-size: 14px;
    font-weight: normal;

    border-radius: 4px;
    line-height: 1.5;
    text-decoration:none;
} 
</style>
</head>

<body>
<div class="divclass" id="repdemo">
</div>
<p><button class="btncls" onclick="replacetxt()">Execute replace method</button></p>
<script type="text/javascript">
var src_str = ("This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. </br>This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters.");
document.getElementById("repdemo").innerHTML = src_str;


function replacetxt(){
var str_rep = src_str.replace("test","<span>TEST</span>");

document.getElementById("repdemo").innerHTML = str_rep;

}

</script>
</body>
</html>

Output as the button is clicked:

JavaScript replace single

As you click the button to execute the replace method, you can see the first occurrence of “test” is replaced by “TEST” (in which the background color is changed). While the other occurrences are unchanged.

To apply replacement on all occurrences, you can use the regular expression (regex) with the global modifier (g).

See the example with code to learn how you can use this.

JavaScript replace regex

JavaScript

<script type="text/javascript">
var src_str = ("This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. </br>This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters.");
document.getElementById("repdemo").innerHTML = src_str;


function replacetxt(){
var str_rep = src_str.replace(/test/g,"<span>TEST</span>");

document.getElementById("repdemo").innerHTML = str_rep;

}

</script>

As you click the button, the replace JavaScript method executes where I used regex with a global modifier:

var str_rep = src_str.replace(/test/g,"<span>TEST</span>");

By that statement, all occurrences of “test” will be replaced by “TEST”.  The <span> tag is used to show it clearly, and uses CSS style. The code is displayed by using this line:

document.getElementById("repdemo").innerHTML = str_rep;

Using replace method as case-insensitive

In the above example, you can see the word “test” occurred four times including with the title-case i.e. “Test”. However, the replace method did not modify it.

To perform case-insensitive modification, you can use “/i” modifier.

In this demo, I have used the same source string as in the above example. This time, all occurrences of the word “test” will be replaced.

JavaScript replace all

The following JS code is used:

<script type="text/javascript">

var src_str = ("This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. </br>This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters.");

document.getElementById("repdemo").innerHTML = src_str;



function replacetxt(){

var str_rep = src_str.replace(/test/gi,"<span>TEST</span>");

document.getElementById("repdemo").innerHTML = str_rep;

}

</script>

Particularly, note this line inside the function:

var str_rep = src_str.replace(/test/gi,"<span>TEST</span>");

By using “g” and “i”, all occurrences irrespective of the case will be replaced in the given string.

A demo of using a variable with regex to replace all

In the above examples of replacing all terms in the source string, I used the static string “test” in the regular expression.

It does not use double quotes like ordinary JavaScript strings. So, if you try placing a variable there, e.g.

var str_rep = src_str.replace(/rep_term/gi,"<span>TEST</span>");

Where rep_term is supposed to be a variable, it will still act as a hard-coded string. Upon executing the above code, the “rep_term” will be searched in the given string instead of its value.

So how can you use variables or user-provided values to act as the replace term that also replaces all occurrences including case-insensitive?

See the following examples – first use a simple variable.

JavaScript replace all variable

HTML, JS, and CSS:

<!DOCTYPE html>
<html>
<head>
<style>
.divclass {
  background: #3B505F;
  height: auto;
  width:350px;
  border-radius: 15px;
  padding:20px;
  font-size:16px;
  color:#fff;  
}
span {
    background: #F7FB4D;
    color:#000;
    font-size:16px;
    font-weight:700;
}
.btncls{
    background-color:#FC2209;
    border: #2e6da4;
  	font-family: Arial, Geneva, Arial, Helvetica,  sans-serif;
	font-size: 15px;
    color: #FFFFFF;
    letter-spacing: 1px;
    padding: 8px 12px;
    font-size: 14px;
    font-weight: normal;

    border-radius: 4px;
    line-height: 1.5;
    text-decoration:none;
} 
</style>
</head>

<body>
<div class="divclass" id="repdemo">This Is A Test Sentence With Titlecase testing variables</br> this is a test sentence with small letters to test variables. </br>This Is A Test Sentence With Titlecase </br>this is a test sentence with small letters. 
</div>
<p><button class="btncls" onclick="replacetxt()">Execute replace method</button></p>
<script type="text/javascript">
var src_str = document.getElementById("repdemo").innerHTML;

function replacetxt(){
    var rep_term = "test";
    var rep_regex = new RegExp(rep_term,"gi");
    var str_rep = src_str.replace(rep_regex,"<span>TEST</span>");

    document.getElementById("repdemo").innerHTML = str_rep;

}

</script>
</body>
</html>

In this example, I have constructed a new RegExp object, where the variable and modifiers are used. See this line inside the replacetxt JS function that executes as you click the button:

 var rep_term = "test";

var rep_regex = new RegExp(rep_term,"gi");

var str_rep = src_str.replace(rep_regex,"<span>TEST</span>");

The output of the above code is replacing all matches with case-insensitive.

A demo to replace all matches with user-selected value

The variable in the above example still contains the hard-coded value. In certain scenarios, you may get the value to be replaced by the visitors of the website.

The replace term can be taken by HTML dropdown for predefined options or textbox etc.

The source string, where the replace term will be checked can be a hard-coded, database-driven, or even a paragraph, div, span, etc element’s text in the current web page.

  • In this demo, I will use the source text from the div element.
  • A user is given the option to select a replacing term from the HTML dropdown.
  • After selecting the term, press the button to apply changes in the div text.

Experience this demo online.

JavaScript replace all select

See online demo and code

In the JS code section, first of all, the div text is assigned to a string variable by using:

var src_str = document.getElementById("repdemo").innerHTML;

As you click the button, the replacetxt function is called where HTML dropdown values are assigned to JS variables:

 var rep_term = document.getElementById("repterm").value;

var rep_to = document.getElementById("reptoterm").value;

This is followed by constructing the RegExp object, where replace term is used and replace all (g) and case-insensitive (i) modifiers are given:

   var rep_regex = new RegExp(rep_term,"gi");

After that, the JS replace method is executed:

  var str_rep = src_str.replace(rep_regex,"<span>" + rep_to + "</span>");

Finally, the replaced string is displayed in the div again that contained initial text:

  document.getElementById("repdemo").innerHTML = str_rep;
Note that, I used two dropdowns for demo only. In pro sites, you may filter the other dropdown based on the first selection or use textboxes, etc.

You can see the complete code with markup and CSS styles on the demo page.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!