簡體   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