【问题标题】:How to remove a complete tag from a string using javascript? [duplicate]如何使用javascript从字符串中删除完整的标签? [复制]
【发布时间】:2019-10-03 17:16:18
【问题描述】:

我的输入如下

input = "hello <script>alert("I am stealing your data");</script>"

我想从字符串中删除完整的脚本标签,输出应该是这样的

output = "hello"

尝试了以下命令,但它没有删除完整的标签。

input.replace(/(<([^>]+)>)/ig, ''));

它给了我们结果

"hello alert("I am stealing you data");"

【问题讨论】:

  • @NinaScholz 缺少什么?这是一个简单直接的问题
  • 没有dv。但是,如果非“hello”部分是恒定的,那么您可以使用以下answer
  • @Dixel 鉴于它是一个 script 标签,我不会认为它是恒定的。这似乎旨在清理任意数据。
  • 它不是恒定的。它是我们从用户那里得到的输入。修复 XSS 攻击的方式
  • 嗯...如果您从服务器获取此字符串,则攻击已经发生。

标签: javascript regex


【解决方案1】:

您应该为此使用not use 正则表达式。而是使用 DOM 解析器功能:

var input = 'hello <script\>alert("I am stealing your data");</script\>';

var span = document.createElement("span");
span.innerHTML = input; // This will not execute scripts
// Remove all script tags within this span element:
Array.from(span.querySelectorAll("script"), script => script.remove()); 
// Get the remaining HTML out of it
var scriptless = span.innerHTML;

console.log(scriptless);

请注意,让用户将任意 HTML 传递给您的应用程序是一个非常糟糕的主意。清理涉及a lot more 而不仅仅是删除脚本标签。

【讨论】:

  • “清理不仅仅是删除脚本标签。” 这取决于你想如何清理你的字符串。一个简单的两个班轮就可以很好地清理一个 html 字符串。 var replacements = { "&amp;": "&amp;amp;", "&lt;": "&amp;lt;", "&gt;": "&amp;gt;", '"': "&amp;quot;", "'": "&amp;apos;" }; str.replace(/[&amp;&lt;&gt;"']/g, match =&gt; replacements[match]);
【解决方案2】:

您不需要使用正则表达式,因为它们很容易被欺骗并且不适合解析 HTML 内容,尤其是不可信的 HTML 内容。

相反,您可以使用DOMParser 创建一个新文档并使用 DOM API 删除所有脚本标签,然后返回其余内容:

function sanitise(input) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(input, "text/html");
  
  let scripts = [...doc.getElementsByTagName('script')]
  
  scripts.forEach(script => script.remove());
  
  return doc.body.textContent.trim();
}

//using the + because otherwise StackSnippets breaks
console.log(sanitise("hello <script>alert('I am stealing your data');</scr"+"ipt>"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 2014-11-07
    • 2011-06-27
    • 2022-10-07
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多