3

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.

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. Commented Aug 8, 2014 at 7:42
  • 1
    text.match(new RegExp('<script src="scripts\/([^\.]+\.scripts)\.js"><\/script>', 'i'))[1] 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. Commented Aug 8, 2014 at 7:52
  • That's why context information is useful. But even node has HTML parsers. Commented Aug 8, 2014 at 7:54
  • Yes you are right @FelixKling. Commented Aug 8, 2014 at 7:55

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I got the gist @hjpotter92 about my mistake and got it working from the above comment.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.