用 html 标签包装文本区域内容

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 代码,我更正了文本区域输入:

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 拆分字符串,然后映射字符串以使用元素 (p) 将其包装起来。终于加入他们了:

var str = `First line...
Second line...
Third line...`;

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