athul777
athul777

Reputation: 207

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. 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!

Upvotes: 1

Views: 1773

Answers (2)

Yasin
Yasin

Reputation: 76

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370699

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.

Upvotes: 4

Related Questions