Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to get src url between script tag

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.

like image 831
Shashank Agrawal Avatar asked Mar 15 '26 04:03

Shashank Agrawal


2 Answers

Your 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]
like image 57
hjpotter92 Avatar answered Mar 16 '26 18:03

hjpotter92


Try /\w+.scripts(?=.js)/ ?

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

Your match pattern is a bit vague. I can simply use /fa9f85fb.scripts/ to match it.

like image 36
stevemao Avatar answered Mar 16 '26 18:03

stevemao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!