IT

HTML 태그를 HTML로 이스케이프하는 가장 빠른 방법은 무엇입니까?

lottoking 2020. 8. 29. 16:06
반응형

HTML 태그를 HTML로 이스케이프하는 가장 빠른 방법은 무엇입니까?


일을 포함 나는하는 크롬 확장 프로그램 쓰고 있어요 많은 문자열 살균 : 작업을 다음 할 수 CHAPTER 2하여, HTML 태그를 포함 <, >&&lt;, &gt;그리고 &amp;각각을,.

(즉, PHP와 동일 htmlspecialchars(str, ENT_NOQUOTES)합니다. 큰 따옴표 문자를 변환 할 필요가 있다고 생각합니다.)

이것은 내가 지금까지 가장 빠른 기능입니다.

function safe_tags(str) {
    return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') ;
}

그러나 한 번에 여러 개의 다중 운영 체제를 실행할 때 여전히 큰 지연이 있습니다.

누구든지 제출 개선 할 수 있습니까? 차이가 대부분의 경우 10 ~ 150 자 사이의 대부분이 사용됩니다.

(내가 가지고있는 것이 한 가지 아이디어는보다 큼 기호를 인코딩하는 것을 귀찮게하지 않는 것이 었습니다. 이로 인해 실제 위험이 있습니까?)


전달 함수를 전달하여 교체를 수행 할 수 있습니다.

var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
};

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function safe_tags_replace(str) {
    return str.replace(/[&<>]/g, replaceTag);
}

다음은 성능 테스트입니다. http://jsperf.com/encode-html-entitiesreplace함수를 반복적으로 호출하고 Dmitrij가 제안한 DOM 메서드를 사용하는 것과 비교 합니다.

당신의 길은 더 빠른 것 ...

그래도 왜 필요합니까?


수행 할 수있는 한 가지 방법은 다음과 있습니다.

var escape = document.createElement('textarea');
function escapeHTML(html) {
    escape.textContent = html;
    return escape.innerHTML;
}

function unescapeHTML(html) {
    escape.innerHTML = html;
    return escape.textContent;
}

여기에서 신청할 수 있습니다.


유형 유형 함수로서의 Martijn의 방법 :

String.prototype.escape = function() {
    var tagsToReplace = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;'
    };
    return this.replace(/[&<>]/g, function(tag) {
        return tagsToReplace[tag] || tag;
    });
};

var a = "<abc>";
var b = a.escape(); // "&lt;abc&gt;"

가장 빠른 방법은 다음과 가능합니다.

function escapeHTML(html) {
    return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
}

이 방법은 'replace'를 기반으로하는 방법보다 약 두 배 빠 사용 합니다. http://jsperf.com/htmlencoderegex/35를 참조하십시오 .

출처 : https://stackoverflow.com/a/17546215/698168


AngularJS 소스 코드에는 angular-sanitize.js 내부 버전도 있습니다 .

var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
    // Match everything outside of normal chars and " (quote character)
    NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
/**
 * Escapes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} escaped text
 */
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, function(value) {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, function(value) {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

올인원 스크립트 :

// HTML entities Encode/Decode

function htmlspecialchars(str) {
    var map = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        "\"": "&quot;",
        "'": "&#39;" // ' -> &apos; for XML only
    };
    return str.replace(/[&<>"']/g, function(m) { return map[m]; });
}
function htmlspecialchars_decode(str) {
    var map = {
        "&amp;": "&",
        "&lt;": "<",
        "&gt;": ">",
        "&quot;": "\"",
        "&#39;": "'"
    };
    return str.replace(/(&amp;|&lt;|&gt;|&quot;|&#39;)/g, function(m) { return map[m]; });
}
function htmlentities(str) {
    var textarea = document.createElement("textarea");
    textarea.innerHTML = str;
    return textarea.innerHTML;
}
function htmlentities_decode(str) {
    var textarea = document.createElement("textarea");
    textarea.innerHTML = str;
    return textarea.value;
}

http://pastebin.com/JGCVs0Ts


더 빠르고 / 짧은 솔루션은 다음과 같습니다.

escaped = new Option(html).innerHTML

이것은 Option 요소가 이러한 종류의 자동 이스케이프를 수행하는 생성자를 유지하는 JavaScript의 이상한 흔적과 관련이 있습니다.

https://github.com/jasonmoo/t.js/blob/master/t.js에 대한 크레딧


function encode(r) {
  return r.replace(/[\x26\x0A\x3c\x3e\x22\x27]/g, function(r) {
	return "&#" + r.charCodeAt(0) + ";";
  });
}

test.value=encode('How to encode\nonly html tags &<>\'" nice & fast!');

/*
 \x26 is &ampersand (it has to be first),
 \x0A is newline,
 \x22 is ",
 \x27 is ',
 \x3c is <,
 \x3e is >
*/
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>


" mark ( javascript에서 사용) 를 처리하는 단일 함수로서 Martijn의 메소드 :

function escapeHTML(html) {
    var fn=function(tag) {
        var charsToReplace = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&#34;'
        };
        return charsToReplace[tag] || tag;
    }
    return html.replace(/[&<>"]/g, fn);
}

속도에 대해서는 잘 모르겠지만 단순성을 찾고 있다면 lodash / underscore 이스케이프 기능을 사용하는 것이 좋습니다 .


쇼에 조금 늦었지만 encodeURIComponent ()decodeURIComponent () 사용에 문제가 있습니까?

참고 URL : https://stackoverflow.com/questions/5499078/fastest-method-to-escape-html-tags-as-html-entities

반응형