need to convert a textarea value to html content with p
tags instead of new lines
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. You can map that with template interpolation to wrap tags around. Utilizing the regex /\\n+/
will ignore multiple succeeding newlines.
const text = "Hello\nWorld!\n\nHello\nmy\nfriend";
const html = text.split(/\n+/).map(e => `<p>${e}</p>\n`);
And a console.log(html);
looks like this:
(5) ["<p>Hello</p>↵", "<p>World!</p>↵", "<p>Hello</p>↵", "<p>my</p>↵", "<p>friend</p>↵"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.