Forum Moderators: open

Message Too Old, No Replies

Putting functions into backreferences

Instead of just returning a string

         

adni18

6:20 pm on Jun 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi, I seem to remember posting about this a while ago, but I can't find the post, and don't remember the answer, so here goes.

Is there a way to (in jscript) call a function with a backreference to a RegExp, rather than just calling "$1" or something?

Example:

tstring="hello <@ 4-3 @>";

alert(tstring.replace(/\<\@\s{1,}(.+)\s{1,}\@\>/g, "eval($1)"));

That simply returns "eval(4-3)", and eval("$1") returns an error. So, is there a way to make sure 4-3 is evaluated (to 1)? Thanks!

adni18

10:02 pm on Jun 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Anyone? Help? Please?

Bernard Marx

6:22 am on Jun 27, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi adni.

tstring="hello <@ 4-3 @>";

alert( tstring.replace(/<@\s+(.+)\s+@>/g,
function(a,b){ return eval(b) }
)
);

adni18

4:43 pm on Jun 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



So jscript will automatically make the arguments $1, $2, $3, and so on?

Bernard Marx

5:41 pm on Jun 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Pretty much. I don't have it down 100% myself. I usually have to investigate. The function may be called multiple times if the g-flag is used, of course.

For the arguments, it appears to go something like this:

1) The substring matching the entire RegExp.
2,3,..) The submatches ($n)
last arg) The entire input string

--- try it out ---

var string="abcde";
var reg = /a(b)(c)/;
var info = "";

function repFn()
{
for(var k=0;k<arguments.length;k++)
info+= k+":"+arguments[k]+"\n";
}

string.replace(reg,repFn)

alert(info)