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. Similarly a URL with a valid script tag like:
https://url.com/something.php?getp=<script>func();</script>
should also return true. However, something like:
https://url.com/something.php?getp=<script</script>
should return false since it is not a valid script tag.
Any advice on how to go about this would be appreciated. Thanks!
Use DOMParser
to turn the string into a document, and then with querySelector
, check to see if the document has any script
tags:
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.
You can use the JavaScript String match...
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.