0

I'm trying to create a regex to get the full file path of an URL. Since I know the input will always be a simple HTTP/HTTPS URL (e.g. http://www.example.org/path/to/file.js?a12345678), I can simply get anything that comes after the third /, including the slash.

The closest answer I found was replace content after tab 5 and 6 (regular expression), but it's a regex to get anything that comes before that character:

"http://www.example.org/path/to/file.js?a12345678".match(/^((?:[^\/]*\/){2})[^\/]*/)

returns

["http://www.example.org", "http://"]

I need it to return ["/path/to/file.js?a12345678"]

I currently use the regex from Regex to get first word after slash in URL but it's wasteful, as I don't need specific path parts, only the full path including query strings and fragment identifier.

Community
  • 1
  • 1

2 Answers2

2

Get the matched group from index 1. ✽ Want to Be Lazy? Think Twice.

https?:\/\/[^/]*(\/.*)

Here is online demo

sample code:

var str="http://www.example.org/path/to/file.js?a12345678";
alert(str.match(/https?:\/\/[^\/]*(\/.*)/i)[1]);
Braj
  • 46,415
  • 5
  • 60
  • 76
2

You can use a regex like this:

https?:\/\/.*?(\/.*)

Working demo

enter image description here

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123