Edit, save, self-modifying HTML document; format generated HTML, JavaScript

Your replace function replaces until the /textarea> that is in your clone variable. It doesn’t do it from the first file because there’s a newline character after textarea in the html. One way to fix it would be to add a newline character in the generated html. Like this:

var clone = ["<!doctype html><head></head><body><textarea>"
          + input.value
         // add newline here
          + "</textarea>\n"
          + "<button>save file</button>"
          + "<script type="text/javascript">"
          + "var saveFile = document.getElementsByTagName('button')[0];"
          + "var input = document.getElementsByTagName('textarea')[0];"
          + "var a = document.createElement('a');"
          + "saveFile.onclick = function(e) {"
          + "var clone="<!doctype html>"+ document.documentElement.outerHTML.replace(/<textarea>.*<.+textarea>/, '<textarea>'+document.getElementsByTagName('textarea')[0].value+'<\/textarea>');"
          + "console.log(clone);"
          + "var file = new Blob([clone], {'type':'text/html'});"
          + "a.href = URL.createObjectURL(file);"
          + "a.download = 'file-' + new Date().getTime() + '.html';"
          + "a.click();"
          + "};"
          + "</scr"+"ipt>"
          + "</body>"
          + "</html>"];

Leave a Comment