Programing

JS 정규식으로 HTML에서 모든 스크립트 태그 제거

lottogame 2020. 12. 6. 20:52
반응형

JS 정규식으로 HTML에서 모든 스크립트 태그 제거


pastebin 에서이 HTML에서 스크립트 태그를 제거하고 싶습니다.

http://pastebin.com/mdxygM0a

아래 정규식을 사용해 보았습니다.

html.replace(/<script.*>.*<\/script>/ims, " ")

그러나 html의 모든 스크립트 태그를 제거하지는 않습니다. 인라인 스크립트 만 제거합니다. 모든 스크립트 태그 (인라인 및 멀티 라인)를 제거 할 수있는 정규식이 필요합니다. 내 샘플 http://pastebin.com/mdxygM0a 에서 테스트를 수행하면 매우 감사하겠습니다 .

감사


정규식을 사용하여 HTML 마크 업을 제거하려는 시도는 문제가 있습니다. 거기에 스크립트 또는 속성 값으로 무엇이 있는지 모릅니다. 한 가지 방법은이를 div의 innerHTML로 삽입하고 스크립트 요소를 제거하고 innerHTML을 반환하는 것입니다.

  function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    return div.innerHTML;
  }

alert(
 stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')
);

현재 브라우저는 innerHTML 속성을 사용하여 삽입 된 경우 스크립트를 실행하지 않으며 특히 요소가 문서에 추가되지 않으므로 절대 실행하지 않을 것입니다.


jQuery는 정규식을 사용하여 경우에 따라 스크립트 태그를 제거하고 개발자가 그렇게 할 타당한 이유가 있다고 확신합니다. 아마 일부 브라우저는 않습니다 사용하여 삽입 할 때 스크립트를 실행 innerHTML.

정규식은 다음과 같습니다.

/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi

그리고 사람들이 "그러나 HTML에 대한 정규식은 악하다"라고 외치기 전에 : 예, 그렇습니다. 하지만 스크립트 태그의 경우 특별한 동작으로 인해 안전합니다. <script>섹션은 </script>이 위치에서 끝나지 않는 한 전혀 포함하지 않을 수 있습니다 . 따라서 정규식과 쉽게 일치시킬 수 있습니다. 그러나 간략히 살펴보면 위의 정규식은 닫는 태그 내부의 후행 공백을 고려하지 않으므로 </script   등이 여전히 작동 하는지 테스트해야 합니다.


정규식은 이길 수 있지만 DOM에 삽입하고 싶지 않은 HTML의 문자열 버전이있는 경우 가장 좋은 방법 일 수 있습니다. 다음과 같은 것을 처리하기 위해 루프에 넣을 수 있습니다.

<scr<script>Ha!</script>ipt> alert(document.cookie);</script>

위의 jquery 정규식을 사용하여 내가 한 작업은 다음과 같습니다.

var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
while (SCRIPT_REGEX.test(text)) {
    text = text.replace(SCRIPT_REGEX, "");
}

이 정규식도 작동합니다.

<script(?:(?!\/\/)(?!\/\*)[^'"]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/.*(?:\n)|\/\*(?:(?:.|\s))*?\*\/)*?<\/script>

내부에 다음과 같은 "문제가있는"변수 문자열을 포함 할 수도 있습니다.

<script type="text/javascript">
   var test1 = "</script>";
   var test2 = '\'</script>';
   var test1 = "\"</script>";
   var test1 = "<script>\"";
   var test2 = '<scr\'ipt>';
   /* </script> */
   // </script>
   /* ' */
   // var foo=" '
</script>

jQuery와 Prototype이 이러한 것들에서 실패한다는 것은 이음새가 있습니다.

'17 년 7 월 31 일 편집 : a) 더 나은 성능을위한 비 캡처 그룹 (및 빈 그룹 없음) 및 b) JavaScript 주석 지원이 추가되었습니다.


Regex 기반 스크립트 태그 정리에 의지해야 할 때마다. 적어도 다음과 같은 형식으로 닫는 태그에 공백을 추가하십시오.

</script\s*>

그렇지 않으면

<script>alert(666)</script   >

태그 이름 뒤의 후행 공백이 유효하기 때문에 남아 있습니다.


jQuery.parseHTML () http://api.jquery.com/jquery.parsehtml/을 사용하지 않는 이유는 무엇 입니까?


제 경우에는 페이지 제목을 구문 분석하고 스크립트를 실행하는 것 외에 jQuery의 다른 모든 장점을 갖추기위한 요구 사항이 필요했습니다. 작동하는 것 같은 내 솔루션이 있습니다.

        $.get('/somepage.htm', function (data) {
            // excluded code to extract title for simplicity
            var bodySI = data.indexOf('<body>') + '<body>'.length,
                bodyEI = data.indexOf('</body>'),
                body = data.substr(bodySI, bodyEI - bodySI),
                $body;

            body = body.replace(/<script[^>]*>/gi, ' <!-- ');
            body = body.replace(/<\/script>/gi, ' --> ');

            //console.log(body);

            $body = $('<div>').html(body);
            console.log($body.html());
        });

This kind of shortcuts worries about script because you are not trying to remove out the script tags and content, instead you are replacing them with comments rendering schemes to break them useless as you would have comments delimiting your script declarations.

Let me know if that still presents a problem as it will help me too.


If you want to remove all JavaScript code from some HTML text, then removing <script> tags isn't enough, because JavaScript can still live in "onclick", "onerror", "href" and other attributes.

Try out this npm module which handles all of this: https://www.npmjs.com/package/strip-js


Here are a variety of shell scripts you can use to strip out different elements.

# doctype
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<\!DOCTYPE\s\+html[^>]*>/<\!DOCTYPE html>/gi" {} \;

# meta charset
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<meta[^>]*content=[\"'][^\"']*utf-8[\"'][^>]*>/<meta charset=\"utf-8\">/gi" {} \;

# script text/javascript
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<script[^>]*\)\(\stype=[\"']text\/javascript[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# style text/css
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<style[^>]*\)\(\stype=[\"']text\/css[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xmlns
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxmlns=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xml:lang
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxml:lang=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with


You can try

$("your_div_id").remove();  

or

 $("your_div_id").html(""); 

Try this:

var text = text.replace(/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/g, "")

참고URL : https://stackoverflow.com/questions/6659351/removing-all-script-tags-from-html-with-js-regular-expression

반응형