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:
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. 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)?
You can split the string with \n
, then map the string to wrap that with the element ( 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.