javascript - 使用捕获组 $1 访问对象的键值

标签 javascript regex javascript-objects

a下面,我尝试通过使用正则表达式定义键来访问存储在对象中的 HTML 实体值,如下所示。然而,我得到的是“ bat 侠未定义的罗宾”而不是“ bat 侠与罗宾”。有人可以向我解释为什么我变得未定义而不是对象的键值属性吗?谢谢!

function convertHtmlEntities ( str ) {

    // Object containing all the key value pair of HTML entities.
    var htmlEntities = {
        "&": "&",
        "<": "&lt;",
        ">": "&gt;",
        '"': "&quot;",
        "'": "&apos;"
    };

    // Regular expression for replacing the items mentioned above with the
    // appropriate HTML entities.
    console.log( str.replace( /([\&\<\>\"\'])+/, htmlEntities['$1'] ) );
    return str.replace( /([\&\<\>\"\'])+/, "$1" );
}

convertHtmlEntities("Batman & Robin"); // Should return "Batman &amp; Robin"

最佳答案

您可以将函数传递给String.replace():

str.replace( /([\&\<\>\"\'])+/, function(match){
    return htmlEntities[match];
});

关于javascript - 使用捕获组 $1 访问对象的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427074/

相关文章:

javascript - 如何在启用 Windows 身份验证的情况下发送 API 请求?

javascript - 在 JavaScript 对象中堆叠过滤器值不起作用

javascript - 将 Web 应用程序嵌入 native iOS 应用程序的最佳方式是什么?

regex - 正则表达式获取两个指定字符之间的任何内容

regex - 否定 RE2 语法中的匹配?

javascript - 执行数组深处的函数

php - Javascript 和 PHP 函数

python - python中的递归正则表达式?

javascript - 将类添加到对象数组中的每个框(JS)

javascript - 如何从对象数组中过滤空值?