JavaScript replace() Method: To replace information in a string, you can use regular expressions and the JavaScript replace() Method of the String object. The syntax for using the JavaScript replace() Method is as follows:
varname= stringname.replace(regex,newstring);
Consider a variable named myVariable containing the string “Today is Sunday”. You could search and replace “Sunday” with “Monday” with the following example with JavaScript replace() Method:
myVariable.replace("Sunday","Monday");
When you use the JavaScript replace() Method it returns a new string containing the results of performing the replacement. The original string is not altered. For instance, consider assigning the results of the replacement above to a new variable:
var newVar = myVariable.replace("Sunday','Monday");
In this case, myVariable will continue to contain “Today is Sunday” but newVar will contain “Today is Monday”. The following task creates a variable and assigns text to it, replaces that text with new text, and then displays the results in a browser:
1. Open a new HTML document in your preferred HTML or text editor.
2. Create the body of the document with opening and closing body tags:
<body> </body>
3. Insert a script block in the body of the document:
<script language="JavaScript"> <!--// --> </script>
4. Create a variable named FirstVariable and assign the value “Hello there” to it:
var FirstVariable = "Hello there";
5. Create a second variable named SecondVariable and assign the results of replacing “there” with “Ecomputernotes” to it:
var SecondVariable = FirstVariable.replace("there","ecomputernotes");
6. Display the results of the JavaScript replace() Method the final page looks like
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>JavaScript replace() Method </title> </head> <body> <h1 style="color: blue"> JavaScript replace() Method</h1> <hr /> <script type="text/javascript"> var FirstVariable = "Hello there"; var SecondVariable = FirstVariable.replace("there","Ecomputernotes"); document.write(SecondVariable); </script> </body> </html>
Save the file and close it.
8. Open the file in a browser. You should see the text “Hello Ecomputernotes” displayed in the browser as in Figure