Forum Moderators: open
Basically what I need to do is use search+replace for about twelve variables at once, rather than executing something like:
new String("apples and oranges").replace(/[stuff1]/g, stuff2).replace(/[stuff3]/g, stuff4);
because, conceivably, anything that stuff2 contains may match something in stuff3. This script needs to replace both stuff1 and stuff3 with both stuff2 and stuff4 at the same time. Any ideas? Thanks!
I suppose it wouldn't be too hard to knock up a generic function that will do it without having to write the individual expressions twice. Here's the idea, anyhow.
str = "apple banana strange orange nipple apples"res = str.replace(
/[ai]pple[b][red]¦[/red][/b]orange/g,
function(m)
{
if(/[ai]pple/.test(m))
return "orange";
else if (/orange/.test(m))
return "apples";
}
);
//
alert(res)
Watch out for those ¦¦ as usual.
[pre]
String.prototype.replaceM = function(pairs, i){
var regM=[];
for(var k=-2,reg;reg=pairs[k+=2];)
regM.push(reg.source); return this.replace(
new RegExp(regM.join("¦"),"g"+(i¦¦"")),
function(m){
for(var k=-2,reg;reg=pairs[k+=2];)
if(reg.test(m))
return pairs[k+1];
}
);
}
pairs = [/[ax]aa/,"bbb",/bbb/,"ccc"]
alert("aaa bbb xaa".replaceM(pairs))
[/pre]