Advertisements
To count the number of words in an HTML document, you can extract the text content of the document and then use a word counting function to count the number of words. Here's an example in JavaScript:
const html = "<html><body><p>Hello, world!</p></body></html>"; const text = new DOMParser().parseFromString(html, "text/html").body.textContent; const wordCount = text.split(" ").length; console.log(wordCount); // Output: 2
This code uses the DOMParser API to parse the HTML string into a DOM tree, then extract the text content of the
<body>
element and split it into words using the split
method. Finally, it counts the number of elements in the resulting array to get the word count.Advertisements
0 Comments