Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用捕获组$1访问对象';s键值_Javascript_Regex_Javascript Objects - Fatal编程技术网

Javascript 使用捕获组$1访问对象';s键值

Javascript 使用捕获组$1访问对象';s键值,javascript,regex,javascript-objects,Javascript,Regex,Javascript Objects,aBelow,我试图访问HTML实体值,该值通过使用正则表达式定义键存储在对象中,如下所示。然而,我得到的是“蝙蝠侠未定义罗宾”,而不是“蝙蝠侠与罗宾”。有人能解释一下为什么我没有定义对象的键值属性吗?谢谢大家! function convertHtmlEntities ( str ) { // Object containing all the key value pair of HTML entities. var htmlEntities = { "&am

aBelow,我试图访问HTML实体值,该值通过使用正则表达式定义键存储在对象中,如下所示。然而,我得到的是“蝙蝠侠未定义罗宾”,而不是“蝙蝠侠与罗宾”。有人能解释一下为什么我没有定义对象的键值属性吗?谢谢大家!

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"
函数转换属性(str){
//对象,该对象包含HTML实体的所有键值对。
变量htmlEntities={
“&”:“&;”,
"": "",
'"': """,
“'”:“&apos;”
};
//正则表达式,用于将上述项替换为
//适当的HTML实体。
log(str.replace(/([\&\\\“\'])+/,htmlEntities['$1']);
返回str.replace(/([\&\\\\“\'])+/,“$1”);
}
《蝙蝠侠与罗宾》;//应该返回“蝙蝠侠与罗宾”
您可以尝试:

str.replace( /([\&\<\>\"\'])+/, htmlEntities[RegExp.$1]
另外,请注意,它的功能可能会随时间被浏览器删除。

您可以尝试:

str.replace( /([\&\<\>\"\'])+/, htmlEntities[RegExp.$1]

另外,请注意,它的功能可能会随时间被浏览器删除。

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

str.replace(/([\&\\\“\'])+/,函数(匹配){
返回属性[匹配];
});

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

str.replace(/([\&\\\“\'])+/,函数(匹配){
返回属性[匹配];
});

感谢您指出这一点。我在发布这篇文章大约15分钟后发现,您还可以将函数传递到String.replace()中,谢谢您指出这一点。发布这篇文章大约15分钟后,我发现您还可以将函数传递到String.replace()中
str.replace( /([\&\<\>\"\'])+/, function(match){
    return htmlEntities[match];
});