【问题标题】:Wrap textarea content with html tags用 html 标签包装 textarea 内容
【发布时间】:2020-04-04 21:55:06
【问题描述】:

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

<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”标签包裹每一行文本。所以,如果我粘贴在 textarea 中:

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

文本应该自动变成:

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

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

【问题讨论】:

    标签: javascript html textarea


    【解决方案1】:

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

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

    【讨论】:

    • 完美!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多