Forum Moderators: open

Message Too Old, No Replies

Regex Issues

Replacing two expressions at once.

         

adni18

10:29 pm on Feb 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey.

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!

DrDoc

10:34 pm on Feb 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Your best bet is to use twelve different regular expressions. While many other languages have array type search and replace, JavaScript does not.

adni18

11:51 pm on Feb 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Oh well. :/. Thanks for the help anyway. :S

Edit: Is there a possibility in VBScript?

Bernard Marx

12:50 am on Feb 19, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So, we're trying to replace a match, but avoid the result being affected by any of the other matches. I think this sort of thing does it.

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)

DrDoc

5:21 am on Feb 19, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



But, twelve variables, Bernard Marx? :o

adni18

3:44 pm on Feb 19, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmm. Maybe something that splits the string, then splits that string and splits that string and so on?

Bernard Marx

8:31 pm on Feb 19, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There are a few angles of attack. So far, I'm going for a generalised version of my previous.

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]