繁体   English   中英

使用 html 标签包装 textarea 内容

[英]Wrap textarea content with html tags

我正在使用以下表单在服务器上保存文本文件:

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

使用以下 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;
};

现在我想用“p”标签包装每一行文本。 所以,如果我粘贴到文本区域:

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

文本应自动变为:

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

如何使用纯 JavaScript(无 jQuery)实现此结果?

您可以使用\n拆分字符串,然后使用 map 将字符串与元素( p )包装起来。 最后加入他们:

 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