Help with efficient RegExp replace() loop

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Will

    #1

    Help with efficient RegExp replace() loop

    I have the following code:

    var rx = /{{(.+?)}}/i;
    var expr = 'each {{word}} wrapped in {{curly}} {{braces}} in this
    {{string}} needs to be {{replaced}} with a different {{value}}.';
    var values = [];
    values["value"] = "foo";
    values["string"] = "bar";
    values["braces"] = "bundy";

    while(expr.matc h(rx)) {
    expr = expr.replace(rx , values[RegExp.$1]);
    }

    Can anyone suggest a more efficient way of writing the match/replace
    loop. Is there any way to do it with a single replace() call only?

    Please note that I'm looking solely at improving the efficiency of the
    while() loop. The actual input string and array of values are
    irrelevant and for demonstration purposes only.

    TIA

    Will
  • Lasse Reichstein Nielsen

    #2
    Re: Help with efficient RegExp replace() loop

    info@whawes.co. uk (Will) writes:
    [color=blue]
    > I have the following code:
    >
    > var rx = /{{(.+?)}}/i;
    > var expr = 'each {{word}} wrapped in {{curly}} {{braces}} in this
    > {{string}} needs to be {{replaced}} with a different {{value}}.';[/color]

    Don't wrap code lines when posting. If your client can't avoid it,
    make sure your lines are no longer than ~72 characters.
    [color=blue]
    > var values = [];
    > values["value"] = "foo";
    > values["string"] = "bar";
    > values["braces"] = "bundy";[/color]

    You should use an object, not an array, for values. I.e.,
    var values = {};
    since you don't use the "arrayness" at all.
    [color=blue]
    > while(expr.matc h(rx)) {
    > expr = expr.replace(rx , values[RegExp.$1]);
    > }[/color]
    [color=blue]
    > Can anyone suggest a more efficient way of writing the match/replace
    > loop. Is there any way to do it with a single replace() call only?[/color]

    expr = expr.replace(/\{\{(.+?)}}/g,function(matc h,word){
    return values[word] || "";
    });


    Remember that "{" is also special in regexps.

    The || "" is for words that are not in the values dictionary. It returns
    the empty string for those.
    [color=blue]
    > Please note that I'm looking solely at improving the efficiency of the
    > while() loop.[/color]

    I don't know if it is more efficient, but it is slightly shorter. :)

    Not all versions of Javascript allow a function as second argument, but
    since you use the non-greedy match (.+?), which is also only in modern
    browsers, I don't think it is a problem (i.e., if it fails, so does the
    non-greedy match).

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    Working...