简体   繁体   English

使用 p 标签将 textarea 值转换为 html 内容

[英]convert textarea value to html content using p tags

need to convert a textarea value to html content with p tags instead of new lines需要使用p标签而不是换行将 textarea 值转换为 html 内容
this is my way - it works - but maybe there is a more native way or a predefined function to do the same这是我的方式 - 它有效 - 但也许有更原生的方式或预定义的功能来做同样的事情

 $('button').on('click', function(){ let a = $('#tx').val(); let html = '<p>' + a.trim().replace('\\n', '</p>\\n<p>') + '</p>'; console.log(html); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea id='tx'> lorem ipsum </textarea> <button>CLICK</button>

In JavaScript you can split by newline and get an array.在 JavaScript 中,您可以按换行符拆分并获取数组。 You can map that with template interpolation to wrap tags around.您可以使用模板插值来映射它以环绕标签。 Utilizing the regex /\\n+/ will ignore multiple succeeding newlines.使用正则表达式/\\n+/将忽略多个后续的换行符。

const text = "Hello\nWorld!\n\nHello\nmy\nfriend";
const html = text.split(/\n+/).map(e => `<p>${e}</p>\n`);

And a console.log(html);还有一个console.log(html); looks like this:看起来像这样:

(5) ["<p>Hello</p>↵", "<p>World!</p>↵", "<p>Hello</p>↵", "<p>my</p>↵", "<p>friend</p>↵"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM