programing

jQuery를 사용하여 HTML 문자열 이스케이프

goodjava 2022. 10. 21. 21:22

jQuery를 사용하여 HTML 문자열 이스케이프

jQuery 문자열에서 HTML을 탈출하는 쉬운 방법을 아는 사람이 있습니까?임의의 문자열을 전달하고 HTML 페이지에 표시하기 위해 적절하게 이스케이프할 수 있어야 합니다(JavaScript/HTML 주입 공격 방지).이를 위해 jQuery를 확장하는 것은 가능하지만, 현재 이 작업을 수행하기 위한 프레임워크에 대해 충분히 알지 못합니다.

콧수염의 해결책도 있습니다.

var entityMap = {
  '&': '&',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;',
  '/': '&#x2F;',
  '`': '&#x60;',
  '=': '&#x3D;'
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}

jQuery를 사용하고 있기 때문에 요소의 속성을 설정할 수 있습니다.

// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";

// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after: 
// <div class="someClass">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>

// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value: 
// &lt;script&gt;alert('hi!');&lt;/script&gt;
$('<div/>').text('This is fun & stuff').html(); // "This is fun &amp; stuff"

출처 : http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

HTML을 얻기 위해 탈출하는 경우 꼭 필요한 것은 세 가지뿐입니다.

html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

'사용하다'와 같은 할 수 ."로로 합니다.&quot;목록이 충분히 커지면 어레이를 사용합니다.

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]
for(var item in findReplace)
    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);

encodeURIComponent() HTML 에 만 이스케이프를 실시합니다.

언더스코어 사용도 간단:

_.escape(string) 

언더스코어는 네이티브 js가 제공하지 않는 많은 기능을 제공하는 유틸리티 라이브러리입니다.언더스코어와 동일한 API이지만 성능을 높이기 위해 다시 작성된 lodash도 있습니다.

이 기능을 하는 작은 함수를 작성했습니다.이다.",&,< ★★★★★★★★★★★★★★★★★」>(하지만 보통은 그것만 있으면 됩니다).1개의 솔루션만 사용한다는 점에서 이전에 제안한 솔루션보다 조금 더 우아합니다. .replace()모든 변환을 수행할 수 있습니다.(EDIT 2: 코드 복잡성을 줄여 함수를 더 작고 깔끔하게 만듭니다. 원래 코드가 궁금하면 이 답변의 끝을 참조하십시오.)

function escapeHtml(text) {
    'use strict';
    return text.replace(/[\"&<>]/g, function (a) {
        return { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];
    });
}

이것은 jQuery를 사용하지 않는 플레인 Javascript입니다.

(에스케이프)/ ★★★★★★★★★★★★★★★★★」' 과민하다

mklement의 코멘트에 따라 편집합니다.

위의 기능을 쉽게 확장하여 임의의 문자를 포함할 수 있습니다.이스케이프할 를 더 둘 다 문자 안)에만 하면 ./[...]/g) 및 의 엔트리를 지정합니다.chr오브젝트(EDIT 2: 이 기능도 같은 방법으로 단축)

function escapeHtml(text) {
    'use strict';
    return text.replace(/[\"&'\/<>]/g, function (a) {
        return {
            '"': '&quot;', '&': '&amp;', "'": '&#39;',
            '/': '&#47;',  '<': '&lt;',  '>': '&gt;'
        }[a];
    });
}

해 주세요.&#39; 엔티티)의 경우&apos;대신 사용되었을 가능성이 있습니다.XML로 정의되어 있습니다만, 원래 HTML 사양에는 포함되어 있지 않기 때문에, 모든 브라우저가 서포트하고 있는 것은 아닙니다.HTML 문자 인코딩에 대한 Wikipedia 문서 참조).또한 16진수보다 10진수 엔티티를 사용하는 것이 더 폭넓게 지원된다는 것을 읽은 적이 있지만, 지금은 그 소스를 찾을 수 없는 것 같습니다.(그리고 16진수 엔티티를 지원하지 않는 브라우저는 많지 않습니다.)

주의: 추가/그리고.'HTML에서 특별한 의미가 없고 이스케이프할 필요가 없기 때문에 이스케이프 문자 목록에는 그다지 유용하지 않습니다.

원래의escapeHtml기능.

EDIT 2: 원래 함수는 변수를 사용했습니다(chr)에 필요한 오브젝트를 저장합니다..replace()콜백또한 이 변수에는 범위를 지정하는 추가 익명 함수가 필요했기 때문에 함수는 (필요 없이) 조금 더 크고 복잡해졌습니다.

var escapeHtml = (function () {
    'use strict';
    var chr = { '"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' };
    return function (text) {
        return text.replace(/[\"&<>]/g, function (a) { return chr[a]; });
    };
}());

두 가지 버전 중 어떤 버전이 더 빠른지 테스트하지 않았습니다.필요한 경우 여기에 정보와 링크를 자유롭게 추가해 주십시오.

파티에 늦었다는 건 알지만 jQuery를 필요로 하지 않는 매우 쉬운 해결책이 있습니다.

escaped = new Option(unescaped).innerHTML;

편집: 따옴표가 이스케이프되지 않습니다.따옴표를 이스케이프해야 하는 유일한 경우는 콘텐츠가 HTML 문자열 내의 속성에 인라인 페이스트되는 경우입니다.이렇게 하는 것이 좋은 디자인이라고는 상상하기 어렵습니다.

편집 3: 가장 빠른 솔루션에 대해서는 Saram에서 위의 답변을 확인하십시오.이게 제일 짧아요.

다음은 깨끗하고 깨끗한 JavaScript 함수입니다."다수"와 같은 텍스트는 "다수"로 이스케이프됩니다.

function escapeHtmlEntities (str) {
  if (typeof jQuery !== 'undefined') {
    // Create an empty div to use as a container,
    // then put the raw text in and get the HTML
    // equivalent out.
    return jQuery('<div/>').text(str).html();
  }

  // No jQuery, so use string replace.
  return str
    .replace(/&/g, '&amp;')
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

마지막 테스트 후 브라우저 간 호환 네이티브 JavaScript(DOM) 솔루션을 빠르고 완벽하게 권장합니다.

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

여러 번 반복할 경우 준비된 변수를 사용하여 수행할 수 있습니다.

//prepare variables
var DOMtext = document.createTextNode("test");
var DOMnative = document.createElement("span");
DOMnative.appendChild(DOMtext);

//main work for each case
function HTMLescape(html){
  DOMtext.nodeValue = html;
  return DOMnative.innerHTML
}

최종 성능 비교(스택 질문)를 보십시오.

Underscore.string lib를 사용해 보십시오.jQuery에서 동작합니다.

_.str.escapeHTML('<div>Blah blah blah</div>')

출력:

'&lt;div&gt;Blah blah blah&lt;/div&gt;'

escape()그리고.unescape()는 HTML이 아닌 URL의 문자열을 부호화/복호화하는 것을 목적으로 합니다.

실제로 다음 스니펫을 사용하여 프레임워크가 필요 없는 트릭을 수행합니다.

var escapedHtml = html.replace(/&/g, '&amp;')
                      .replace(/>/g, '&gt;')
                      .replace(/</g, '&lt;')
                      .replace(/"/g, '&quot;')
                      .replace(/'/g, '&apos;');

콧수염이 향상되었습니다.js 예제 추가escapeHTML()string 객체에 메서드를 지정합니다.

var __entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

String.prototype.escapeHTML = function() {
    return String(this).replace(/[&<>"'\/]/g, function (s) {
        return __entityMap[s];
    });
}

그렇게 하면 꽤 사용하기 쉽다."Some <text>, more Text&Text".escapeHTML()

언더스코어.js가 있는 경우_.escape(위의 jQuery 메서드보다 효율적입니다):

_.escape('Curly, Larry & Moe'); // returns: Curly, Larry &amp; Moe

regex 루트를 사용하는 경우 위의 tghw 예에 오류가 있습니다.

<!-- WON'T WORK -  item[0] is an index, not an item -->

var escaped = html; 
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g,"&gt;"], [/"/g,
"&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(item[0], item[1]);   
}


<!-- WORKS - findReplace[item[]] correctly references contents -->

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);
}

이것은 좋은 안전한 예다.

function escapeHtml(str) {
    if (typeof(str) == "string"){
        try{
            var newStr = "";
            var nextCode = 0;
            for (var i = 0;i < str.length;i++){
                nextCode = str.charCodeAt(i);
                if (nextCode > 0 && nextCode < 128){
                    newStr += "&#"+nextCode+";";
                }
                else{
                    newStr += "?";
                }
             }
             return newStr;
        }
        catch(err){
        }
    }
    else{
        return str;
    }
}

바닐라 js로 쉽게 할 수 있어요.

단순히 텍스트 노드를 문서에 추가합니다.브라우저로 이스케이프됩니다.

var escaped = document.createTextNode("<HTML TO/ESCAPE/>")
document.getElementById("[PARENT_NODE]").appendChild(escaped)

JQUERY가 필요 없는 두 가지 간단한 방법...

문자열 내의 모든 문자를 다음과 같이 인코딩할 수 있습니다.

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

아니면 그냥 주인공들이 걱정돼서& 줄 바꿈,<,>," ★★★★★★★★★★★★★★★★★」'들면 다음과 같습니다.

function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}

var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!';

test.value=encode(myString);

testing.innerHTML=encode(myString);

/*************
* \x26 is &ampersand (it has to be first),
* \x0A is newline,
*************/
<p><b>What JavaScript Generated:</b></p>

<textarea id=test rows="3" cols="55"></textarea>

<p><b>What It Renders Too In HTML:</b></p>

<div id="testing">www.WHAK.com</div>

(function(undefined){
    var charsToReplace = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;'
    };

    var replaceReg = new RegExp("[" + Object.keys(charsToReplace).join("") + "]", "g");
    var replaceFn = function(tag){ return charsToReplace[tag] || tag; };

    var replaceRegF = function(replaceMap) {
        return (new RegExp("[" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join("") + "]", "gi"));
    };
    var replaceFnF = function(replaceMap) {
        return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; };
    };

    String.prototype.htmlEscape = function(replaceMap) {
        if (replaceMap === undefined) return this.replace(replaceReg, replaceFn);
        return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap));
    };
})();

전역 변수도 없고 메모리 최적화도 가능합니다.사용방법:

"some<tag>and&symbol©".htmlEscape({'©': '&copy;'})

결과는 다음과 같습니다.

"some&lt;tag&gt;and&amp;symbol&copy;"

플레인 JavaScript 이스케이프 예시:

function escapeHtml(text) {
    var div = document.createElement('div');
    div.innerText = text;
    return div.innerHTML;
}

escapeHtml("<script>alert('hi!');</script>")
// "&lt;script&gt;alert('hi!');&lt;/script&gt;"

ES6 콧수염 솔루션용 라이너 1개.js

const escapeHTML = str => (str+'').replace(/[&<>"'`=\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;',"'": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);
function htmlEscape(str) {
    var stringval="";
    $.each(str, function (i, element) {
        alert(element);
        stringval += element
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(' ', '-')
            .replace('?', '-')
            .replace(':', '-')
            .replace('|', '-')
            .replace('.', '-');
    });
    alert(stringval);
    return String(stringval);
}
function htmlDecode(t){
   if (t) return $('<div />').html(t).text();
}

아주 효과가 있다

속도 최적화 버전:

function escapeHtml(s) {
   let out = "";
   let p2 = 0;
   for (let p = 0; p < s.length; p++) {
      let r;
      switch (s.charCodeAt(p)) {
         case 34: r = "&quot;"; break;  // "
         case 38: r = "&amp;" ; break;  // &
         case 39: r = "&#39;" ; break;  // '
         case 60: r = '&lt;'  ; break;  // <
         case 62: r = '&gt;'  ; break;  // >
         default: continue;
      }
      if (p2 < p) {
         out += s.substring(p2, p);
      }
      out += r;
      p2 = p + 1;
   }
   if (p2 == 0) {
      return s;
   }
   if (p2 < s.length) {
      out += s.substring(p2);
   }
   return out;
}

const s = "Hello <World>!";
document.write(escapeHtml(s));
console.log(escapeHtml(s));

이스케이프 html 스페셜용(UTF-8)

function htmlEscape(str) {
  return str
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\//g, '&#x2F;')
      .replace(/=/g,  '&#x3D;')
      .replace(/`/g, '&#x60;');
}

unescape html specials(UTF-8)의 경우

function htmlUnescape(str) {
  return str
      .replace(/&amp;/g, '&')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&#x2F/g, '/')
      .replace(/&#x3D;/g, '=')
      .replace(/&#x60;/g, '`');
}

이 정보를 데이터베이스에 저장하는 경우 클라이언트 측 스크립트를 사용하여 HTML을 이스케이프하는 것이 올바르지 않습니다.이 작업은 서버에서 수행해야 합니다.그렇지 않으면 XSS 보호를 무시하기 쉽습니다.

제 요점을 명확히 하기 위해 다음 중 하나의 답변을 사용한 예를 제시하겠습니다.

excapeHtml 함수를 사용하여 블로그의 댓글에서Html을 이스케이프하여 서버에 투고하고 있다고 합시다.

var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

사용자는 다음을 수행할 수 있습니다.

  • POST 요청 파라미터를 편집하여 javascript 코드로 코멘트를 바꿉니다.
  • 브라우저 콘솔을 사용하여 excapeHtml 함수를 덮어씁니다.

사용자가 콘솔에 이 스니펫을 붙여넣으면 XSS 검증이 생략됩니다.

function escapeHtml(string){
   return string
}

답변은 jQuery 및 일반 JS 메서드를 제공하지만 DOM을 사용하지 않는 것이 가장 짧습니다.

unescape(escape("It's > 20% less complicated this way."))

" " " " "It%27s%20%3E%2020%25%20less%20complicated%20this%20way.

이스케이프된 공간이 불편할 경우 다음을 시도해 보십시오.

unescape(escape("It's > 20% less complicated this way.").replace(/%20/g, " "))

" " " " "It%27s %3E 20%25 less complicated this way.

도 ★★★★★★★★★★★★★★★★★.escape()함수는 JavaScript 버전 1.5에서 더 이상 사용되지 않습니다.encodeURI() ★★★★★★★★★★★★★★★★★」encodeURIComponent() 수단이지만 '코드 마지막 행은 다음과 같습니다.

decodeURI(encodeURI("It's > 20% less complicated this way.").replace(/%20/g, " ").replace("'", '%27'))

모든 주요 브라우저가 여전히 쇼트 코드를 지원하며 오래된 웹사이트의 수를 감안할 때 그것은 곧 바뀔 것 같지 않다.

를 들어 대부분의 은 계속 됩니다.예를 들어 대부분의 솔루션은 계속 회피됩니다.&로로 합니다.&amp;.

escapeHtml = function (s) {
    return s ? s.replace(
        /[&<>'"]/g,
        function (c, offset, str) {
            if (c === "&") {
                var substr = str.substring(offset, offset + 6);
                if (/&(amp|lt|gt|apos|quot);/.test(substr)) {
                    // already escaped, do not re-escape
                    return c;
                }
            }
            return "&" + {
                "&": "amp",
                "<": "lt",
                ">": "gt",
                "'": "apos",
                '"': "quot"
            }[c] + ";";
        }
    ) : "";
};

언급URL : https://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery