Skip to content

Instantly share code, notes, and snippets.

@ikasoba
Last active April 14, 2022 11:52
Show Gist options
  • Save ikasoba/579a812524053c7542ff5ab3b94a9439 to your computer and use it in GitHub Desktop.
Save ikasoba/579a812524053c7542ff5ab3b94a9439 to your computer and use it in GitHub Desktop.
jsでhtmlを組み立てるやつ
/**
* @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