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

Ferrmolina
  • 2,737
  • 2
  • 30
  • 46
  • 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) { ... }`. – Phylogenesis Mar 26 '15 at 09: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 – user2484927 Mar 26 '15 at 09:54

2 Answers2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
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.

Community
  • 1
  • 1
Phylogenesis
  • 7,775
  • 19
  • 27