简体   繁体   中英

regex check if there are any valid script tags in string

i want to match script tag in a HTML string where there might or might not be comments.

Some examples,

<!-- <script>...</script> --> <script src='test.js'></script>
<!-- <script>...</script> -->

I only want to match the first example.

This is what i have come up with, but it does not work, any help is appreciated. thanks

/(<!--.*?-->)*.*<script[\s>\/]/gmi

Parse your string with DOMParser to get HTML tree, then use querySelectorAll to count elements.

See the snippet below:

 var str = "<!-- <script>...<\\/script> --> <script src='test1.js'><\\/script><!-- <script>...<\\/script> --><script src='test2.js'><\\/script>"; var parser = new DOMParser(); var doc = parser.parseFromString(str, 'text/html'); var howManyScripts = doc.querySelectorAll('script').length; console.log(howManyScripts);

尝试使用这个正则表达式:

<script src=['"]{1}.+['"]{1}>[.\s]*<\/script>

This regex works in most script tag cases

Eg. <script src="myscript.js"></script>

/([<&][az]*[;]*)(script( .+[=]["'].+["'])*)([>&]*[az]*[;]*)([^>]*([<&][az]*[;]*)*(\\/script)([>&]*[az]*[;]*))*/gi

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.

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