简体   繁体   English

用于检查字符串是否包含有效脚本标记的正则表达式

[英]Regex expression for checking if a string contains a valid script tag

I am trying to create a regex expression that tests whether a given string has a valid script tag.我正在尝试创建一个正则表达式来测试给定字符串是否具有有效的脚本标记。 If for example a page contains within it例如,如果一个页面包含在其中

<body>Body goes here</body>
<script src = "page.js"></script>

Testing this string (the HTML source of the page in this case) with the regex test method should return true since there is a valid script tag.使用正则表达式测试方法测试此字符串(在这种情况下为页面的 HTML 源)应返回 true,因为存在有效的脚本标记。 Similarly a URL with a valid script tag like:类似地,带有有效脚本标签的 URL 如下:

https://url.com/something.php?getp=<script>func();</script>

should also return true.也应该返回 true。 However, something like:但是,类似:

https://url.com/something.php?getp=<script</script>

should return false since it is not a valid script tag.应该返回 false,因为它不是有效的脚本标签。

Any advice on how to go about this would be appreciated.任何有关如何 go 的建议将不胜感激。 Thanks!谢谢!

Use DOMParser to turn the string into a document, and then with querySelector , check to see if the document has any script tags:使用DOMParser将字符串转换为文档,然后使用querySelector检查文档是否有任何script标签:

 const hasScript = str => Boolean( new DOMParser().parseFromString(str, 'text/html').querySelector('script') ); console.log(hasScript('https://url.com/something.php?getp=<script<\/script>')); console.log(hasScript('https://url.com/something.php?getp=<script><\/script>')); console.log(hasScript(`<body>Body goes here</body> <script src = "page.js"><\/script>`)); console.log(hasScript('https://url.com/something.php?getp=<script>func();<\/script>'));

DOMParser is safe - the content of the script tags won't be executed during parsing. DOMParser安全的——脚本标签的内容在解析过程中不会被执行。

You can use the JavaScript String match...您可以使用 JavaScript 字符串匹配...

let str = 'abcdefi<script>jfdjjdjd'; 
let  valueToLookFor = /script/g
let isItThere = str.match(valueToLookFor);
isItThere ? console.log('Yes'):console.log('No') //yes

let str = 'abcdefijfdjjdjd'; 
let  valueToLookFor = /script/g
let isItThere = str.match(valueToLookFor);
isItThere ? console.log('Yes'):console.log('No') //no

This should do it.这应该这样做。

/(<script\s*>\w.+<\/script\s*>)|(<script\s*src\s*=\s*"[A-Za-z0-9]+\.js"\s*><\/script\s*>)/g

Try this in regexr正则表达式中试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM