Shoutbox

[?] "Dynamic" RegExp replace... - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Messenger Plus! for Live Messenger (/forumdisplay.php?fid=4)
+---- Forum: Scripting (/forumdisplay.php?fid=39)
+----- Thread: [?] "Dynamic" RegExp replace... (/showthread.php?tid=98162)

[?] "Dynamic" RegExp replace... by whiz on 08-16-2011 at 05:57 PM

Not sure on the best way to go about this...

Here's an example of what I want to do.

jscript code:
// a "dynamic" object - identifiers will vary by function
var some_variables =
{
    foo: "some text",
    bar: "some more text"
};

// user input - can contain such variables when surrounded with "%"
var input = "I am writing %var:foo% here.";
var regex = /%var:([a-z]+?)%/gi;
var output = input.replace(regex, some_variables[regex.$1]);
...but I just get undefined from the RegExp.  Is there a way of doing this?
RE: [?] "Dynamic" RegExp replace... by Eljay on 08-16-2011 at 06:19 PM

Don't think you can do it in one replace call, you can always just loop through them:

js code:
for(var key in some_variables)
    input = input.replace(new RegExp("%var:"+key+"%", "gi"), some_variables[key]);

RE: [?] "Dynamic" RegExp replace... by whiz on 08-16-2011 at 06:54 PM

Hmm, didn't think of that.  Works a treat, thanks!


RE: [?] "Dynamic" RegExp replace... by Matti on 08-17-2011 at 02:22 PM

The reason why your version won't work is because regexp.$1 is evaluated once when that line is run.

However, you can still do this without a for-loop and lots of replace calls. JScript allows you to pass a function as second parameter for replace, whose return value will be used as replacement for each match. When using regular expressions, it'll even give you all the good stuff through the function's arguments!

js code:
var output = input.replace(regex, function(match, $1) {
    // You could do literally anything here!
    return ($1 in some_variables) ? some_variables[$1] : '';
});

RE: [?] "Dynamic" RegExp replace... by whiz on 08-17-2011 at 06:20 PM

Looks like I could do some more advanced stuff with that...  might be easier to implement stuff later on.  Thanks for that!  :P