Search and Replace Strings
By Stephen Bucaro
To search a string for a substring and replace that substring within the string you can use
the String object's .substring method to find the substring and break up the initial
string, and use the concatenation operator (+) to reconstruct the initial string with
the replacement substring.
In the example shown below, I search for the phrase "wags it's tail" in the text and replace it
with the phrase "wiggles it's ears".
<script>
var initialStr = "a dog growls when it's angry and wags it's tail when it's pleased.";
var searchStr = "wags it's tail";
var loc1 = initialStr.indexOf(searchStr);
var leftStr = initialStr.substring(0,loc1);
var loc2 = searchStr.length + loc1;
var len2 = initialStr.length;
var rightStr = initialStr.substring(loc2,len2);
var finalStr = leftStr + "wiggles it's ears" + rightStr;
alert(finalStr);
</script>
In the code, I use the .indexOf method to get the location of the first character of
the search phrase with the main string. Then I use the .substring method to save the
left side of the main string.
Next I use the location of the first character of the search phrase along with the .length
method to get the location of the end of the search phrase within the main string. Using the
location of the end of the search phrase, and the length of the main string, I use the
.substring method to save the right side of the main string.
Lastly, I use the concatenation operator to string together the left side of the main string,
the replacement phrase, and the right side of the main string. This creates the final text
"a dog growls when it's angry and wiggles it's ears when it's pleased."
What if you're not sure that the initial text will contain the searched for substring? The .indexOf
method returns -1 if it can't find the value of its parameter in the string, so you would use code
similar to that shown below to test the return value and not perform the replace.
<script>
var initialStr = "a dog growls when it's angry and wags it's tail when it's pleased.";
var searchStr = "wags it's tail";
var loc1 = initialStr.indexOf(searchStr);
if(loc1 > -1)
{
var leftStr = initialStr.substring(0,loc1);
var loc2 = searchStr.length + loc1;
var len2 = initialStr.length;
var rightStr = initialStr.substring(loc2,len2);
var finalStr = leftStr + "wiggles it's ears" + rightStr;
alert(finalStr);
}
</script>
One last note: The String object also has a substr method, as opposed to .substring.
Whereas the .substring method's parameters are character locations within the string, the
substr method's parameters specify the starting character location and the number of
characters to be included in the substr.
More Java Script Code: • Interactively Set Webpage Colors • Java Script Data Types • Remove Blank Spaces From Ends of a String • Java Script Math.tan Method • Generating Random Numbers • Cookie Power Made Easy • The while Loop • Java Script Strings • Compare Two Strings • The Document Object Model (DOM)
|