使用捕获组 $1 访问对象的键值
Using capture group $1 to access object's key value
a 下面,我尝试访问 HTML 实体值,该实体值存储在如下所示的对象中,方法是使用正则表达式定义键。但是,我得到 "Batman undefined Robin" 而不是 "Batman & Robin"。有人可以向我解释为什么我得到的是 undefined 而不是对象的键值 属性 吗?谢谢!
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[''] ) );
return str.replace( /([\&\<\>\"\'])+/, "" );
}
convertHtmlEntities("Batman & Robin"); // Should return "Batman & Robin"
你可以试试:
str.replace( /([\&\<\>\"\'])+/, htmlEntities[RegExp.]
这将 return(至少对我来说是这样):
"Batman & Robin"
另外,请注意这是 deprecated,它的功能可能会被浏览器随时删除。
你可以传递一个函数给String.replace()
:
str.replace( /([\&\<\>\"\'])+/, function(match){
return htmlEntities[match];
});
a 下面,我尝试访问 HTML 实体值,该实体值存储在如下所示的对象中,方法是使用正则表达式定义键。但是,我得到 "Batman undefined Robin" 而不是 "Batman & Robin"。有人可以向我解释为什么我得到的是 undefined 而不是对象的键值 属性 吗?谢谢!
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[''] ) );
return str.replace( /([\&\<\>\"\'])+/, "" );
}
convertHtmlEntities("Batman & Robin"); // Should return "Batman & Robin"
你可以试试:
str.replace( /([\&\<\>\"\'])+/, htmlEntities[RegExp.]
这将 return(至少对我来说是这样):
"Batman & Robin"
另外,请注意这是 deprecated,它的功能可能会被浏览器随时删除。
你可以传递一个函数给String.replace()
:
str.replace( /([\&\<\>\"\'])+/, function(match){
return htmlEntities[match];
});