Search code examples
javascripthtmljqueryprettier

How do I put this raw code to a <pre> tag properly?


I am trying to let the user enter in some text, then I run prettier on it and then show the user the formatted code. My fiddle:

<pre id="mypre" style="background-color:grey"></pre>

var val = `"<!DOCTYPE html>\n
<html>
  \n
  <body>
    \n
    <h1>My First Heading</h1>
    \n
    <p>My first paragraph.</p>
    \n\n
  </body>
  \n
</html>
"`;


$(document).ready(function(){
  val = val.replace(/^"(.*)"$/, '$1');
  val = val.replace(/(?:\r\n|\r|\n)/g, '');
  $("#mypre").text(val);
});

Note that the returned text comes back with literal " and I've tried replacing them and the \n character to no avail. I'd like the pre tag to look like this:

<!DOCTYPE html>
<html>
  <body>
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
  </body>
</html>

Solution

  • Yeah, regex is fun. This should work:

    var val = `"<!DOCTYPE html>\n
    <html>
      \n
      <body>
        \n
        <h1>My First Heading</h1>
        \n
        <p>My first paragraph.</p>
        \n\n
      </body>
      \n
    </html>
    "`;
    
    
    $(document).ready(function(){
      val = val.replace(/^"([\s\S]*?)"$/, '$1');
      val = val.replace(/\n{2,}/g, '');
      $("#mypre").text(val);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <pre id="mypre" style="background-color:grey"></pre>

    The first regex ([\s\S]*?) matches everything across multiple lines and \n{2,} matches two or more \n line breaks.