0

I'm trying to create a regex which finds a text that contains :

  1. src
  2. .js

and does not contain a question mark '?' at the same time.

For example I want my regex to match :

src="scripts/test.js"

and not match :

src="Servlet?Template=scripts/test.js" 

because it contains a question mark sign.

Can anyone give me the appropriate regex?

Thanks a lot

2
  • 1
    This is one of those times when I would probably prefer to read if (str.indexOf('src') !== -1 && str.indexOf('.js') !== -1 && str.indexOf('?') === -1) { ... }. Commented Mar 26, 2015 at 9:49
  • I wish I can use it ,but I'm dealing with a full template text so it might contain several occurrences of 'src' with '.js' and I want to alter each occurrence of src Commented Mar 26, 2015 at 9:54

2 Answers 2

2

You can use this regex:

/\bsrc=(?!.*?\?).+?\.js\b/i

(?!.*?\?) is negative lookahead that means fail the match when there is a ? following src= in input string.

Sign up to request clarification or add additional context in comments.

11 Comments

thank you ! I tried it but it passed this text <script language="JavaScript" src="apps/core/scripts/frameset/buttons.js"></script>
Of course it did. Your specification asked for it to match that.
@user2484927: Why it should not match <script language="JavaScript" src="apps/core/scripts/frameset/buttons.js"></script> ?
I'm using in Java , Pattern and Matcher classes : Pattern p= Pattern.compile("/=\\bsrc=(?!.*?\\?).+?\\.js\\b"); Matcher m= p.matcher(strTemplateText); m.find() is returning false even though strTemplatetext contains <script language="JavaScript" src="apps/core/scripts/frameset/buttons.js"></script> @anubhava @Phylogenesis
Java‽ The tag in your question says JavaScript. They are completely different languages.
|
1

You seem to be wanting to parse/make changes to HTML with regex, but since you're using JavaScript, you already have a fully functional DOM parser available to you.

How about the following:

var scripts = document.querySelectorAll('script[src]');

for (var i = 0; i < scripts.length; i++) {
    var src = scripts[i].getAttribute('src');

    if (/\.js$/.test(src) && src.indexOf('?') === -1) {
        alert(src);
    }
}

Example jsFiddle here.

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.