By Stephen Bucaro
You have a string with multiple occurrences of a substring within and you want to replace every occurrence
of that substring with a different substring. Two built-in string methods make this operation extremely easy.
The .split method splits a string into pieces at a substring that you specify and returns the substrings as an array.
The .join method joins all elements of an array separating each element of the array with a substring
that you specify, and returns a single string.
You can combine the call to the .split method and .join method to perform the operation in a single statement.
document.write("Original String:<br /><br />");
var strOriginal = "The blooming, bloody spider went up the spider web. The blooming, bloody rain came down and washed the spider out. The blooming, bloody sun came out and dried up all the rain. And the blooming, bloody spider came up the web again.";
document.write("<br /><br />Modified String:<br /><br />");
var strModified = strOriginal.split("blooming, bloody").join("itsy bitsy");
The example code above takes the string "The blooming, bloody spider went up the spider web. The blooming, bloody rain
came down and washed the spider out. The blooming, bloody sun came out and dried up all the rain. And the blooming, bloody
spider came up the web again." and replaces the substrings "blooming, bloody" within it with "itsy bitsy".
More Java Script Code:
• Calculators for Your Website : Decimal to Hexidecimal Converter
• Regular Expressions Boundaries
• Easy Rollovers
• Play Music on Your HTML5 Web Page
• Calculators for Your Website : Fahrenheit to Celsius Converter
• Using the Java Script Date Object
• Regular Expressions Intervals
• Java Script Message Boxes
• HTML5 and Local Storage