I wanted to get name of the script from such a string:
var text = '<script src="scripts/044c7c5e.vendor.js"></script><script src="scripts/fa9f85fb.scripts.js"></script>'
I wanted to retrieve the second script name i.e. fa9f85fb.scripts. How can I achieve this using javascript regex?
I'm writing something like this:
text.match(new RegExp(/<script src="scripts\/[(.*?)]\.scripts\.js"><\/script>/), 'g')[0]
But its returning the whole string.
I wanted to get name of the script from such a string:
var text = '<script src="scripts/044c7c5e.vendor.js"></script><script src="scripts/fa9f85fb.scripts.js"></script>'
I wanted to retrieve the second script name i.e. fa9f85fb.scripts. How can I achieve this using javascript regex?
I'm writing something like this:
text.match(new RegExp(/<script src="scripts\/[(.*?)]\.scripts\.js"><\/script>/), 'g')[0]
But its returning the whole string.
Share Improve this question asked Aug 8, 2014 at 7:39 Shashank AgrawalShashank Agrawal 25.8k11 gold badges96 silver badges125 bronze badges 5-
1
Or better: parse the HTML to DOM and access the
src
attribute. Browsers are great in parsing HTML. FYI,RegExp
expects a string, not a regular expression. – Felix Kling Commented Aug 8, 2014 at 7:42 - 1 text.match(new RegExp('<script src="scripts\/([^\.]+\.scripts)\.js"><\/script>', 'i'))[1] – GramThanos Commented Aug 8, 2014 at 7:45
- Thanks @FelixKling for your reply but I'm using regex in a grunt task, so was not using the HTML parser in browser. – Shashank Agrawal Commented Aug 8, 2014 at 7:52
- That's why context information is useful. But even node has HTML parsers. – Felix Kling Commented Aug 8, 2014 at 7:54
- Yes you are right @FelixKling. – Shashank Agrawal Commented Aug 8, 2014 at 7:55
2 Answers
Reset to default 4Your pattern grabbing is a bit off; [(.*?)]
should instead be (.*?)
simply:
/<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g
will be the entire regex, no need to call the RegExp
class constructor either. The matched string is stored at index 0
. The various segments are then stored from index 1
onwards.
text.match( /<script src="scripts\/(.*?)\.scripts\.js"><\/script>/g )[1]
Try /\w+.scripts(?=.js)/
?
Reference: https://developer.mozilla/en/docs/Web/JavaScript/Guide/Regular_Expressions
Your match pattern is a bit vague. I can simply use /fa9f85fb.scripts/ to match it.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745450029a4628226.html
评论列表(0条)