but not

Regular expression to match <script type = "text / javascript"> but not <script type = "text / html">

current code (doesn't work):

/^script\s*type=\"text\/javascript/i.test(tagName) 
+4
source share
5 answers

To account for the β€œtype” that appears anywhere in the script tag and multiple versions of quotes, use:

 /<script.*?type\s*=\s*.text\/javascript./i 

You can tighten it by specifying all alternate quotation marks instead of ".".

0
source

Regular expressions and HTML are bad things. How will regex work for the following examples (don't forget about single and double quotes)?

 <script type="text/javascript"> <script language="JavaScript" type="text/javascript"> <script type="text/javascript" language="JavaScript"> <script class="myJS" type="text/javascript"> <script type="text/javascript" class="myJS" > 

Instead of regular expressions, I suggest using a function like this:

 function attr_in_str(str, tag, attr) { var div = document.createElement('div'); div.innerHTML = str; var elems = div.getElementsByTagName(tag); for (var i = 0; i < elems.length; i++) { if (elems[i].type.toLowerCase() == attr.toLowerCase()) { return true; } } return false; } 

Then use it:

 var str = 'This is my HTML <script type="text/javascript"></script>'; var result = attr_in_str(str, 'script', 'text/javascript'); 
+2
source

Assuming you know all the assumptions when you use a regular expression to process HTML.

You can simply remove ^ in your current code, since it matches the beginning of a line.

EDIT

The number of spaces must be at least 1, so you must change * after \s to +

+1
source
 /<script\stype\=\"text\/javascript\">/i 
+1
source

I'm not a big fan of regex, so I would do this:

 var temp = document.createElement('div'); temp.innerHTML = '<script type="text/html"></script>'; var type = temp.childNodes[0].getAttribute('type'); if (type == 'text/javascript') { // ... } 

If you use jQuery this will be easier:

 if ($('<script type="text/html"></script>').prop('type') == 'text/javascript') { // ... } 
+1
source

All Articles