Fastest method to escape HTML tags as HTML entities?

前端 未结 12 1545
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:24

I\'m writing a Chrome extension that involves doing a lot of the following job: sanitizing strings that might contain HTML tags, by converting

12条回答
  •  一整个雨季
    2020-11-22 09:35

    I'll add XMLSerializer to the pile. It provides the fastest result without using any object caching (not on the serializer, nor on the Text node).

    function serializeTextNode(text) {
      return new XMLSerializer().serializeToString(document.createTextNode(text));
    }
    

    The added bonus is that it supports attributes which is serialized differently than text nodes:

    function serializeAttributeValue(value) {
      const attr = document.createAttribute('a');
      attr.value = value;
      return new XMLSerializer().serializeToString(attr);
    }
    

    You can see what it's actually replacing by checking the spec, both for text nodes and for attribute values. The full documentation has more node types, but the concept is the same.

    As for performance, it's the fastest when not cached. When you do allow caching, then calling innerHTML on an HTMLElement with a child Text node is fastest. Regex would be slowest (as proven by other comments). Of course, XMLSerializer could be faster on other browsers, but in my (limited) testing, a innerHTML is fastest.


    Fastest single line:

    new XMLSerializer().serializeToString(document.createTextNode(text));

    Fastest with caching:

    const cachedElementParent = document.createElement('div');
    const cachedChildTextNode = document.createTextNode('');
    cachedElementParent.appendChild(cachedChildTextNode);
    
    function serializeTextNode(text) {
      cachedChildTextNode.nodeValue = text;
      return cachedElementParent.innerHTML;
    }
    

    https://jsperf.com/htmlentityencode/1

提交回复
热议问题