Javascript 解析字符串中脚本标记的内容
假设我有以下字符串:Javascript 解析字符串中脚本标记的内容,javascript,regex,Javascript,Regex,假设我有以下字符串: var myString = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>" 我尝试了myString.split(/[]/),但没有得到预期的输出 非常感谢您的帮助。 相反,您可以使用 var-element=docume
var myString = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>"
我尝试了myString.split(/[]/)
,但没有得到预期的输出
非常感谢您的帮助。
相反,您可以使用
var-element=document.createElement('div');
element.innerHTML=myString;//正确解析HTML(但不安全)
然而,这并不安全。即使innerHTML
没有在script
元素中运行JS,恶意字符串仍然可以运行任意JS,例如使用
为了避免这个问题,您可以使用创建一个新文档,该文档可以用作沙盒
var doc=document.implementation.createHTMLDocument();//沙箱
doc.body.innerHTML=myString;//正确解析HTML
或者,新浏览器支持:
var doc=new DOMParser().parseFromString(myString,'text/html');
一旦HTML字符串被解析到DOM中,您就可以使用诸如或之类的DOM方法来获取所有脚本
元素
var scriptElements=doc.getElementsByTagName('script');
最后,可用于获取每个脚本
元素的数组
var arraysscriptcontents=[].map.call(脚本元素,函数(el)){
返回el.textContent;
});
完整的代码是
var doc=document.implementation.createHTMLDocument();//沙箱
doc.body.innerHTML=myString;//正确解析HTML
[].map.call(doc.getElementsByTagName('script')、函数(el){
返回el.textContent;
});
您必须像这样转义正斜杠:/
myString.split(/(<script>|<\/script>)/)
myString.split(/(|)/)
Javascript代码:
function myFunction() {
var str = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>";
console.log(str.match(/<script\b[^>]*>(.*?)<\/script>/gm));
}
函数myFunction(){
var str=“helloconsole.log('hello')Testconsole.log('world')”;
console.log(str.match(/]*>(.*)/gm));
}
您可能想签出,但不要为此使用正则表达式。我建议不要使用这个字符串,而是从这个字符串创建一个实际的DOM元素。然后,您将能够直接访问不同的标签及其内容。有关更多信息和技术,请参阅。@i_t rope您需要使用split还是可以使用其他方法进行此操作?碎片不够吗?一些浏览器会在添加时执行脚本吗?PS:地图会在什么变量中结束?我喜欢看到epic链接。@mplungjan JS inscript
元素在使用innerHTML
创建时从不运行。但是,可能会运行其他JS代码,例如
。因此,我使用了“.”那么字符串在哪里呢?您映射并拥有一个数组[],但保存它们的变量在哪里?@mplungjan调用[]。map
返回所需的数组。它可以分配给某个变量:var arr=[].map.call(/*…*/)
。
function myFunction() {
var str = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>";
console.log(str.match(/<script\b[^>]*>(.*?)<\/script>/gm));
}