I use the following code to extract text from html.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>"
var text = extractContent(html);
console.log("TEXT: " + text);
function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
}
the result of this code is the text without new lines. but I want the result to replace divs with "\\n" like this:
first line."\n"second line. "\n" third line."\n"
Use s.replaceAll(' ', '\\\\n');
to replace the linefeed.
Note: The backslash \\
needs to be escaped with another \\
.
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>" var text = extractContent(html); console.log("TEXT: " + text); function extractContent(s) { var span = document.createElement('span'); s = s.replaceAll(' ', '\\\\n'); span.innerHTML = s; return span.textContent || span.innerText; }
document.createElement
is not necessary, you can use regexp
alone to achieve this:
var html = "first line. <div>second line. </div><div>third line.</div><div><br></div>" var text = extractContent(html); console.log("TEXT: " + text); function extractContent(s) { /* * /(<[^>]+>)+/gim <---- this regexp to match all html tags and replace them with \\n, * also merge empty content html tags into one \\n * */ return s.replace(/(<[^>]+>)+/gim, "\\n"); }
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.