简体   繁体   English

使用 html 标签包装 textarea 内容

[英]Wrap textarea content with html tags

I'm using the following form to save text files on server:我正在使用以下表单在服务器上保存文本文件:

<form action="***.php" method="post">
   <textarea class="chrr" name="text" placeholder="Text" required></textarea>
   <button type="submit">SAVE</button>
</form>

With the following javascript code, I correct the textarea input:使用以下 javascript 代码,我更正了 textarea 输入:

const form = document.forms[0];
const string = document.getElementsByClassName("chrr");

form.oninput = () => {
   string[0].value = correct(string[0].value);
};

function correct(string) {
   string = string.replace(/  +/g, ' ');
   string = string.replace(/—|–/g, '-');
   string = string.replace(/‘|’/g, "'");
   string = string.replace(/“|”/g, '"');
   string = string.replace(/…/g, '...');
   return string;
};

Now I would like to wrap every single text line with "p" tags.现在我想用“p”标签包装每一行文本。 So, if I paste in the textarea:所以,如果我粘贴到文本区域:

First line...
Second line...
Third line...

The text should automatically become:文本应自动变为:

<p>First line...</p>
<p>Second line...</p>
<p>Third line...</p>

How can I achieve this result with pure JavaScript (no jQuery)?如何使用纯 JavaScript(无 jQuery)实现此结果?

You can split the string with \n , then map the string to wrap that with the element ( p ).您可以使用\n拆分字符串,然后使用 map 将字符串与元素( p )包装起来。 Finally join them:最后加入他们:

 var str = `First line... Second line... Third line...`; str = str.split('\n').map(s => `<p>${s}</p>`).join('\n'); console.log(str);

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

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