admin管理员组

文章数量:1193389

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!

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!

Share Improve this question edited Mar 5, 2010 at 21:27 Gumbo 655k112 gold badges791 silver badges851 bronze badges asked Mar 5, 2010 at 21:23 richrich 811 gold badge1 silver badge2 bronze badges 1
  • So you want the replace to be different depending on the line endings? Also, \n and \r\n can both be called newlines or line breaks. I think a use case might be beneficial here. – cmptrgeekken Commented Mar 5, 2010 at 21:31
Add a comment  | 

2 Answers 2

Reset to default 24

\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.

本文标签: stringReplace n with ltbrgt and rn with ltpgt in javascriptStack Overflow