如何用JavaScript中的对象文字值替换全局RegExp匹配

时间:2013-05-16 17:09:54

标签: javascript regex replace global object-literal

在尝试简单替换时,我尝试过这样的事情:

var dict =
 {
 ...
 };

var selector = ("'$greetings' '$friend'").replace(/\$([^']+)/g, dict[RegExp.$1])

但是只有一个匹配的字符串被相应键的值替换。

1 个答案:

答案 0 :(得分:0)

使用函数作为第二个参数产生了预期的效果:

var selector = ("'$greetings' '$friend'").replace(/\$([^']+)/g, expand)

function expand(match, offset, fullstring)
  {
  var dict =
    {
    ...
    };

  ...
  }

可以将其推广到tokenizer中,例如:

/* Get all anchors with the javascript: URI scheme */
$("a[href*='javascript']").each(function () {
    javascriptURL(arguments[1])
})

/* Replace the javascript: URI with the URL within it */
function javascriptURL(anchor) {
    var hyperlink = $(anchor).attr("href").replace(/./g, replacer).substring(1).replace(/'/g, "");

    /* Class name for new window binding */
    var newWindow = "extWin";

    $(anchor).attr({
        "href": hyperlink,
        "class": newWindow
    });
}

/* Grab all text between window.open() parens */
function replacer(match, offset, fullstring) {
    var tokens = {
        "(": true,
        ",": false,
        ";": false
    };

    /* Consume everything after the left paren */  
    if (tokens[match] === true) {
        replacer.state = true
    }

    /* Discard everything after the first comma; also reset after a semicolon */
    if (tokens[match] === false) {
        replacer.state = false
    }

    /* Continue consuming or discarding otherwise */    
    if (tokens[match] === undefined) {
        replacer.state = replacer.state;
    }

    /* Return the consumed string or an empty string depending on the tokenizer state */
    if (replacer.state === true) {
        return match
    } 
    else {
        return "";
    }

}
  

function replace(pattern:*,repl:Object):String

     

repl:Object - 通常,插入的字符串代替匹配的内容。但是,您也可以将函数指定为此参数。如果指定了一个函数,则插入函数返回的字符串代替匹配的内容。

<强>参考