var strippedHtml = ("<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute</p></div>").replace(/<[^>]+>/g, '');
var strippedHtml = (document.createRange().createContextualFragment("<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute</p></div>").textContent || '');
function convertToPlain(html){
var tempDivElement = document.createElement("div");
tempDivElement.innerHTML = html;
return tempDivElement.textContent || tempDivElement.innerText || "";
}
var htmlString= "<div><h1>Bears Beets Battlestar Galactica </h1>\n<p>Quote by Dwight Schrute</p></div>";
var strippedHtml = convertToPlain(convertToPlain);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
replace | |
createContextualFragment | |
innerHTML |
Test name | Executions per second |
---|---|
replace | 3045352.8 Ops/sec |
createContextualFragment | 111504.5 Ops/sec |
innerHTML | 28821.0 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks, comparing the performance of different approaches for various tasks.
The provided benchmark definition and test cases demonstrate three alternative methods for stripping HTML tags from a string:
replace()
methodcreateContextualFragment
method (introduced in Internet Explorer 8)innerHTML
Testing What's Tested
The testing measures the performance of each approach in removing HTML tags from an input string. The benchmark prepares an example HTML string and then applies one of the three methods to remove the tags.
Comparison of Approaches
This is a built-in JavaScript method that replaces all occurrences of a pattern with another value. In this case, it's used to remove HTML tags by replacing them with an empty string.
Pros:
Cons:
This method was introduced in Internet Explorer 8 as a way to create a contextually fragment of an HTML document. In this benchmark, it's used to remove HTML tags by taking the text content of the created fragment.
Pros:
Cons:
createContextualFragment
with textContent
This custom implementation creates a temporary <div>
element, sets its innerHTML
property to the input HTML string, and then returns the text content of the element.
Pros:
Cons:
replace()
methodOther Considerations
"..."
) to define the input HTML string. This is not a standard way of defining strings in JavaScript, but it's commonly used for this purpose.Alternative Approaches
Other approaches that could be tested on MeasureThat.net include:
These additional tests would provide a more comprehensive understanding of the performance and security characteristics of these approaches.