简体   繁体   中英

regex pattern for match with extension of URL

I have these sample URLs:

1) example.com/foo.js
2) example.com/foo.js?
3) example.com/foo.js?bar

4) example.com/foo.jsbar
5) example.com/foo.js/bar

I want regex js for match with 1, 2, 3 and don't match with 4, 5. with extension.

I use this pattern in LiveHTTP headers add-on firefox .

Firstly I write this:

.js$

This just point to the 1.

And this:

.js\?

Point to the 2, 3.

And this:

.js\??$

Point to 1, 2.

So finally I write this:

.js$|.js\?

This works well.

Test online: https://regex101.com/r/BU5IqH/2

Now my question is how can I have a regex with use once .js string in the pattern?

Brief

My answer is slower than @Wiktor's answer , but more readable. That being said:

  • If readability is your main concern use my answer.
  • If performance is your main concern use @Wiktor's answer .

Code

See regex in use here

\.js(?:\?|$)

In the comments below your question you said I could remove ?: , so in that case the regex would be \\.js(\\?|$)

Usage

 var a = [ 'example.com/foo.js', 'example.com/foo.js?', 'example.com/foo.js?bar', 'example.com/foo.jsbar', 'example.com/foo.js/bar', 'asasa.com/asasas.css', 'asasa.com/asasas.gif']; var r = /\\.js(?:\\?|$)/; a.forEach(function(s) { console.log(s + ': ' + r.test(s)); }); 


Explanation

  • \\.js Match .js literally
  • (?:\\?|$) Match either of the following
    • \\? Match the question mark character ? literally
    • $ Assert position at the end of the line

You want to match .js that is followed with ? or end of string.

Use

/\.js(?![^?])/

Details

  • \\. - a dot
  • js - a js substring
  • (?![^?]) - that is not followed with a char other than ? (so, there can only be a match if there is ? or end of string) immediately to the right of the current location.

See the JS demo:

 var strs = [ 'example.com/foo.js', 'example.com/foo.js?', 'example.com/foo.js?bar', 'example.com/foo.jsbar', 'example.com/foo.js/bar']; var rx = /\\.js(?![^?])/; for (var s of strs) { console.log(s, "=>", rx.test(s)); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM