本文介绍了我如何使用JQuery删除所有“脚本”一串HTML中的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一串HTML代码。我希望使用JQuery从字符串中删除所有< script> 标签。



注意:我想使用JQuery而不是REGEX来执行此操作。



这是否工作正常? $(var).find('script')。remove();

解决方案


  var stringOfHtml = //你的字串在这里
$(stringOfHtml) 。.find( '脚本')除去();

使用脚本标记去除新字符串:

  < 
var html = $(stringOfHtml);
html.find('script')。remove();

var stringWithoutScripts = html.wrap(< div>)。parent()。html(); //必须包装html以获得外部元素



JS小提琴示例与脚本文本


Suppose I have a string of HTML code. I want to use JQuery to remove all <script> tags from the string.

How can I do that?

Note: I want to use JQuery , not REGEX, to do this.

Does this work? $(var).find('script').remove();

解决方案

This should work for you:

var stringOfHtml = // your string here
$(stringOfHtml).find('script').remove();

To get the new string with the script tags removed:

var stringOfHtml = "<div><script></script><span></span></div>";
var html = $(stringOfHtml);
html.find('script').remove();

var stringWithoutScripts = html.wrap("<div>").parent().html(); // have to wrap for html to get the outer element

JS Fiddle Example - Had to use p instead of script as script broke the fiddle, same principle though.

Actual working answer here (hopefully)

Here is a workaround for the script issue, use replace to swap the script text with something else (try and make it unique) then remove those new tags and use replace again to swap back in case script is used anywhere else in text. Yes, it does use regex, but not to remove the script tags so I'm hoping that's alright ;):

var stringOfHtml = "<p></p><script>alert('fail');</scr" + "ipt><span></span>";
var wrappedString = '<div>' + stringOfHtml + '</div>';
var noScript = wrappedString.replace(/script/g, "THISISNOTASCRIPTREALLY");
var html = $(noScript);
html.find('THISISNOTASCRIPTREALLY').remove();

alert(html.html().replace(/THISISNOTASCRIPTREALLY/g, 'script'));

JS Fiddle Workaround

JS Fiddle Example With Script Text

这篇关于我如何使用JQuery删除所有“脚本”一串HTML中的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 08:11