Yehudah
Yehudah

Reputation: 65

Use regex to match URL up to the last forward slash

Trying to extract the value from:

<img src="https://www.google.com/one/two/three/file.png"/>"https://www.google.com/one/file.jpg"

to:

"https://www.google.com/one/two/three/" "https://www.google.com/one/"

I basically want to capture everything in the base url to the last forward slash.

I've tried using /https://([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/ which captures the entire url but I can't figure out how to stop the match at the last '/' of the URL in the html file

Upvotes: 1

Views: 190

Answers (2)

xystum
xystum

Reputation: 1009

If your are sure about the format, you could use:

https?:\/\/[^/"]+([^/"]+\/)+

Where

  • https?:\/\/[^/"]+ matches https:// and everything up to the first / and
  • ([^/"]+\/)+ matches one or more instances of abc/

See also: https://regex101.com/r/6ohuWP/1

Upvotes: 1

Dhruv Kumar
Dhruv Kumar

Reputation: 36

Try split split() method, this make your problem much more simpler

function str(str_url){
 var arr = str_url.split('/');   //splits url at every '/'
 arr.pop();    //this pops the last term in url
 str_url = arr.join('/');    //finally joins everything 
 return str_url;
}

Read more about it at MDN web docs

Upvotes: 1

Related Questions