a下面,我尝试通过使用正则表达式定义键来访问存储在对象中的 HTML 实体值,如下所示。然而,我得到的是“ bat 侠未定义的罗宾”而不是“ bat 侠与罗宾”。有人可以向我解释为什么我变得未定义而不是对象的键值属性吗?谢谢!
function convertHtmlEntities ( str ) {
// Object containing all the key value pair of HTML entities.
var htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
};
// 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 & Robin"
最佳答案
您可以将函数传递给String.replace()
:
str.replace( /([\&\<\>\"\'])+/, function(match){
return htmlEntities[match];
});
关于javascript - 使用捕获组 $1 访问对象的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427074/