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

How do I replace global RegExp matches with object literal values in JavaScript

本文关键字:替换 全局 RegExp 匹配 文字 对象 何用 JavaScript      更新时间:2023-09-26

在一个简单的替换尝试中,我尝试这样做:

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

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

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

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

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

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

引用

  • 字符串对象:替换方法- Adobe ActionScript®3 (AS3) API参考

  • ECMAScript 6新增正则表达式特性

  • Regexp.prototype.replace

  • 使用状态机解析ColdFusion中的标记化数据

  • JavaScript:一个基于状态机的词法分析器+递归下降(LL(k))语法分析器+抽象语法树(AST) +生成器- bl.ocks.org

  • 词法分析程序/词法分析程序。go at master·eczarny/lexer·GitHub

  • GNU C预处理器内部:Lexer