Last active
April 14, 2022 11:52
-
-
Save ikasoba/579a812524053c7542ff5ab3b94a9439 to your computer and use it in GitHub Desktop.
jsでhtmlを組み立てるやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @example | |
* html("div",{class:"hogehoge"},[ | |
* html("p",{},"i am salmon!!"), | |
* "<script>alert('raw html is not embeddable');</script>" | |
* ]); | |
*/ | |
const html = (name,attrs,...children) => ((children.length==1) && void(children[0] instanceof Array) && (children=children[0])) || {name:name,attrs:attrs,children:children,toString(){return `<${this.name} ${Object.entries(this.attrs).map(([k,v])=>(void(v=v.replace(/"|'|<|>/g,([c])=>"&x"+(c.charCodeAt(0).toString(16))+";")) || `${k}=${v?.match("'") ? '"'+v+'"' : v.match(/"|[\s]/) ? "'"+v+"'" : v}`)).join(" ")}>${children.map(x=>typeof x === "string" ? x.replace(/"|'|<|>/g,([c])=>"&#x"+(c.charCodeAt(0).toString(16))+";") : x.toString()).join("")}</${name}>`}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment