Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created May 16, 2024 14:44
Show Gist options
  • Save Pamblam/d9c81b523cb2fd7f54a7dc5544ce33ce to your computer and use it in GitHub Desktop.
Save Pamblam/d9c81b523cb2fd7f54a7dc5544ce33ce to your computer and use it in GitHub Desktop.
run in the console to convert js strings containing HTML to formatted template strings
(async ()=>{
let val = document.querySelector('textarea') ? document.querySelector('textarea').value : '';
document.body.innerHTML = `<textarea style='width: 100vw; height: 100vh'></textarea>`;
document.querySelector('textarea').value = val;
document.querySelector('textarea').addEventListener('input', function(){
oninput(this.value)
});
if(val) oninput(val);
function oninput(str){
console.clear();
str = str.trim();
str = str.replace(/'/g, '`');
str = str.replace(/`\s*\+\s*\n\s*`/g, "\n")
str = str.replace(/`\s*\+\s*`/g, '');
str = str.replace(/`\s*\+([^\+]+)\+\s*`/g, '${$1}');
str = str.replace(/\${\s*([^\s\}]+)\s*\}/g, '${$1}');
str = str.replace(/"`"/g, '`"`');
str = str.replace(/`\s*\+\s*`/g, '');
str = str.replace(/`\s*\+([^\+]+)\+\s*`/g, '${$1}');
str = str.replace(/\${\s*([^\s\}]+)\s*\}/g, '${$1}');
// tags that have an opening and a closing tag
let tags = [...str.matchAll(/<([A-Za-z]+)/g)]
.map(a=>a[1].toLowerCase())
.filter((v,i,s)=>i==s.indexOf(v)&&str.toLowerCase().indexOf(`</${v.toLowerCase()}`)>-1);
let tokens = [];
str.replace(/\s+/g, ' ').replace(/\n/g, '').replace(/>/g, ">\n").split("\n").forEach(t=>{
let textnode = t.match(`^[^<]+`);
if(textnode){
tokens.push(textnode[0]);
tokens.push(t.substring(textnode[0].length))
}else{
tokens.push(t);
}
});
console.log(tokens);
let indents = 0;
let lines = [];
for(let i=0; i<tokens.length; i++){
let indent_added = false;
if(tokens[i].indexOf('<') === 0){
for(let n=0; n<tags.length; n++){
if(tokens[i].toLowerCase().indexOf(`<${tags[n]}`) === 0){
indents++;
indent_added = true;
break;
}
if(tokens[i].toLowerCase().indexOf(`</${tags[n]}`) === 0){
indents--;
break;
}
}
}
lines.push(`${"\t".repeat(Math.max(indent_added?indents-1:indents, 0))}${tokens[i]}`);
}
console.log(lines.join("\n"));
console.log(str);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment