Monday, February 21, 2011

Replace \n with <br> and \r\n with <p> in javascript

Hi All,

I need JS that will remove any HTML tags, and then replace newlines with </p><p> and line breaks with <br/>. The string value is coming from a textarea and I understand Linux, Mac and Windows all format newlines differently so I need to take that into account. Thanks!

From stackoverflow
  • \n and \r\n are equivalent. Linux uses the former, Windows uses the latter.

    What you want to do is replace all cases of \n\n and \r\n\r\n with <p></p> and case of simply \n or \r\n with <br />

    result = "<p>" + text + "</p>";
    result = result.replace(/\r\n\r\n/g, "</p><p>").replace(/\n\n/g, "</p><p>");
    result = result.replace(/\r\n/g, "<br />").replace(/\n/g, "<br />");
    

    This assumes there is no html in your text.

  • I think

    value.replace(/\\n\\n/g, "</p><p>");
    value.replace(/\\n/g, "<br/>");
    

    will do the trick.

0 comments:

Post a Comment