I have searched for a general solution to this but only find answers to peoples specific questions.
Basically, I want to know how to generally use .replace() to repl
What you are looking for are called regular expressions. For more information, you can visit a site like: http://www.regular-expressions.info/
Note that regular expressions are not specific to JavaScript.
For your specific example:
string.replace(/abc.+xyz/,"abc"+newString+"xyz");
. means any character, and + means one or more occurences.
If you have more than one replacement to do, try:
string.replace(/abc.+?xyz/g,"abc"+newString+"xyz");
g stands for general, and ? is the lazy quantifier, meaning that it will stop at the next occurence of xyz in the string.
String.prototype.replaceBetween = function(opentag, closetag, replacement) {
var read_index = 0;
var open_index = 0;
var close_index = 0;
var output = '';
while ((open_index = this.indexOf(opentag, read_index)) != -1) {
output += this.slice(read_index, open_index) + opentag;
read_index = open_index + opentag.length;
if ((close_index = this.indexOf(closetag, read_index)) != -1) {
if (typeof replacement === 'function') {
output += replacement(this.substring(open_index + opentag.length, close_index - 1)) + closetag;
} else {
output += replacement + closetag;
}
read_index = close_index + closetag.length;
}
}
output += this.slice(read_index);
return output
};
var mydiv = document.getElementById("mydiv");
var html = mydiv.innerHTML;
html = html.replaceBetween("<b>", "</b>", "hello");
html = html.replaceBetween("<b>", "</b>", function(body) {
return body + ' world';
});
mydiv.innerHTML = html;
<div id="mydiv">The begining...<b>for</b> and <b>bar</b>... the end.</div>