Replacing text with the replace () method

If you want to make changes to an existing string value, you could use the replace () method. By using this method, you can change some specific part of a whole string. For instance, you could replace the word "JavaScript" with "Master" "Scripting JavaScript." Following shows the JavaScript code to replace that string:

<script language="javascript">
var str1, str2;
str1 = "Scripting JavaScript";
document.write ("Original string: " + str1 + "<br>");
str2 = str1.replace ("JavaScript", "Master");
document.write ("String after replacement: " + str2);
</script>

In the above code, we start by declaring two variables: str1 and str2. The str1 variable holds our "Scripting JavaScript" string (see line 3) and the str2 variable is assigned the replaced string (see line 5). Notice on line 5 we are passing two arguments to the replace () method. The first argument in parentheses contains the string we are searching for. The second argument contains the string that will replace the string that we are searching for, if found. Because the string "JavaScript" is in the "Scripting JavaScript" string, "JavaScript" is replaced with "Master", resulting in as output of the code shows:

If you have been following the other JavaScript examples on this site, you may notice that it is the first time here we are using the "+" operator to combine HTML code with the variables or other strings we want to print (see lines 4 and 6). We could have rewritten those lines as follows but our code becomes little longer:

document.write ("Original string: ");
document.write (str1);
document.write ("<br>");
document.write ("String after replacement: ");
document.write (str2);

Now, let's make another point: the replace () method won't make any changes if the substring that you want to replace in a string is not found. Consider the following example:

<script language="javascript">
var str1, str2;
str1 = "Scripting JavaScript";
document.write ("Original string: " + str1 + "<br>");
str2 = str1.replace ("HTML", "Master");
document.write ("String after replacement: " + str2);
</script>

For simplicity, we are using almost the same code that we used before except now we are trying to replace the string "HTML" in "Scripting JavaScript." with "Master"; Because "HTML" is not in "Scripting JavaScript", no change is made to "Scripting JavaScript" and the following shows the output of the code to support that conclusion: