Search and Replace Using the replace() Method
string.replace(find this string,replace it with this)
The replace() method is super handy. It actually searches for specified string, and replaces it with a new string.
The method's arguments can be string literals or variables, and regular expressions. To use this method effectively, you will need to determine
two things:
first, does your script needs to replace a defined string only once or each time it occurs (globally), and second,
will your arguments (parameters) be string literals or variables. Answering those questions will determine how you construct the arguments.
Here is a simple example of the replace method in action using literals:
var sentence = "I love oranges."
sentence = sentence.replace("oranges","apples");
Lets define a term to replace which occurs more than once in the string:
var sentence = "I love oranges. Oranges are the sweetest fruit.";
sentence = sentence.replace("oranges","apples");
Why did only the first occurance of "orange" change to apples?
There are two reasons: first, the method defaults to replacing only the first instance of a term. We have to tell it to replace the term globally.
How?
By using regular expression notation (forward slashes / instead of quotes) followed the global switch (g), as in the example below.
Note: you can only use reg exp for the first argument of the replace method.
var sentence = "I love oranges. Oranges are the sweetest fruit.";
sentence = sentence.replace(/oranges/g,"apples");
Why did only the first occurance of "orange" change to apples, even though the global switch was added?
The 2nd instance of orange in var sentence begins with an UPPERcase "O". Adding the global switch didn't work because the regular expression
notation defaults to CASE-SENSITIVE. Use the ignore case switch (i) to ignore the case of the term to be replaced.
var sentence = "I love oranges. Oranges are the sweetest fruit.";
sentence = sentence.replace(/oranges/gi,"apples");
You noticed the lowercase "a", didn't you? As you can see, the twists and turns involved in the replacing of strings can and does get
hairy very quickly, but this information is
adequate to get you on the right path, if not complete the job altogether.
You can use a string variable for both the first and second argument of the replace method:
sentence = sentence.replace(document.myform.mytext1.value, document.myform.mytext1.value);
Using a string variable for the method's first parameter is only problematic if your script needs to replace text
globally, e.g. you can't say /document.myform.mytext1.value/g because that notation only works with literals. You
can, however use the regular expression constructor to call a string variable from replace()'s first paramater, and
give it the global switch:
sentence = sentence.replace(new Reg Exp(document.myform.mytext1.value,"g"), document.myform.mytext1.value);
Play around with the working example below to further understand notational restrictions.