最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript regex to get src url between script tag - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 4

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]

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.

发布评论

评论列表(0)

  1. 暂无评论