// HTML和实体相互转换
String.prototype.convertEntity=(function(){
// 字符实体表
let entity = {
quot : '"',
lt : '<',
gt : '>',
amp : '&',
nbsp : ' '
}
let entity_cover_key='',entity_cover={};
for(let item in entity){
entity_cover_key+=entity[item];
entity_cover[entity[item]]='&'+item+';';
}
return function(type){
if(type == 1){
return this.replace(/&([^&;]+);/g,function(a,b){
return typeof entity[b] === 'string' ? entity[b] : a;
})
}else{
let reg=new RegExp('['+entity_cover_key+']','g')
return this.replace(reg,function(c){
return entity_cover[c];
});
}
}
})()
console.log('"><& &asds;'.covert(1)); // ""><& "
console.log('<div>121212</div>'.covert()); // <div>121212</div>