input = "hello <script>alert("I am stealing your data");</script>"
我想从字符串中删除完整的脚本标记,输出应该是这样的
output = "hello"
试过以下命令,但不删除完整标记。
input.replace(/(<([^>]+)>)/ig, ''));
它给我们带来了结果
"hello alert("I am stealing you data");"
宝慕林4294392
浏览 494回答 2
2回答
侃侃无极
您不应该使用正则表达式。而是使用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 itvar scriptless = span.innerHTML;console.log(scriptless);请注意,让用户将任意HTML传递给您的应用程序是一个非常糟糕的主意。清理涉及的不仅仅是删除脚本标记。