Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active January 30, 2016 11:47
Show Gist options
  • Save gaogao-9/6323f8dec4f62a27f6fb to your computer and use it in GitHub Desktop.
Save gaogao-9/6323f8dec4f62a27f6fb to your computer and use it in GitHub Desktop.
class HtmlSpecialChars{
constructor(list){
if(typeof(list) === "undefined") return;
this.escapeList = list;
}
set escapeList(value){
if(typeof(value) !== "object"){
throw new TypeError("escapeListはObject型のプロパティです");
}
this._escapeList = value;
const keys = Object.keys(this._escapeList);
const values = keys.map(key=>{
return this._escapeList[key];
});
this._unescapeList = keys.reduce((obj,key,i)=>{
obj[values[i]] = key;
return obj;
},{});
this._escapeRegExp = new RegExp(`(${keys.join("|")})`,"g");
this._unescapeRegExp = new RegExp(`(${values.join("|")})`,"g");
}
get escapeList(){ return this._escapeList; }
get unescapeList(){ return this._unescapeList; }
get escapeRegExp(){ return this._escapeRegExp; }
get unescapeRegExp(){ return this._unescapeRegExp; }
escape(str){
return str.replace(this.escapeRegExp,$0=>this.escapeList[$0]);
}
unescape(str){
return str.replace(this.unescapeRegExp,$0=>this.unescapeList[$0]);
}
}
/* usage
const h = new HtmlSpecialChars({
'&': '&',
'<': '&lt;',
'>': '&gt;'
});
console.log("エスケープ");
const escapedStr = h.escape('<script>alert("XSS");</script>');
console.log(escapedStr); // '&lt;script&gt;alert(&quot;XSS&quot;);&lt;/script&gt;'
console.log("アンエスケープ");
const unescapedStr = h.unescape(escapedStr);
console.log(unescapedStr); // '<script>alert("XSS");</script>;'
*/
@petamoriken
Copy link

神:sushi::sushi::sushi:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment