0

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

var dict =
 {
 ...
 };

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

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

4

1 回答 1

0

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

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

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

  ...
  }

这可以概括为分词器,例如:

/* 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 "";
    }

}

函数替换(模式:*,repl:对象):字符串

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

参考

于 2013-05-16T17:09:53.980 回答