简体   繁体   中英

regular expression to match <script type=“text/javascript”> but not <script type=“text/html”>

当前代码(不起作用):

/^script\s*type=\"text\/javascript/i.test(tagName)
/<script\stype\=\"text\/javascript\">/i

Regular expressions and HTML — bad things. How regex will work for next 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 to use 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');

Assuming that you are aware of all the assumption when you use regex to process HTML.

You can just remove the ^ in your current code, since it matches the start of the string.

EDIT

Number of spaces should be at least 1, so your should change the * after \\s into +

I'm not a big fan of regex, so I'd 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 were using jQuery, it would be way easier:

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

To account for the 'type' appearing anywhere within the script tag, and multiple versions of quotes, use:

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

You could tighten it up by specifying all quote alternatives instead of '.'.

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