1

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>
user72840184
  • 49
  • 3
  • 13

1 Answers1

2

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.

Tad Wohlrapp
  • 1,848
  • 1
  • 13
  • 18
  • Why does `\n{2,}` match a linebreak as well as the `\n` literal? I'm kinda confused. – user72840184 May 05 '20 at 04:34
  • @user72840184 `\n` is the line break, on Linux at least. As I haven't seen any `\r\n` (Windows) line breaks in your code, I supposed that should suffice. To be extra safe you could of course match for `(\r\n|\r|\n)` followed by `{2,}`, so `(\r\n|\r|\n){2,}` to cover all possibilities. See this question for more info: [Match linebreaks - \n or \r\n?](https://stackoverflow.com/a/20056634/1275152) – Tad Wohlrapp May 05 '20 at 04:35
  • 1
    @user72840184 In case you're wondering about the `{2,}`: this just means match two or more of the preceding expression. In this case the preceding expression is our line break, so "match two or more linebreaks". One line break is just a new line, which we want to keep, but two line breaks in a row represent an empty line, which I think you wanted to remove, right? – Tad Wohlrapp May 05 '20 at 05:20