Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find base name in URL in Javascript

I want to extract the base name from a image URL in Javascript. Would somebody care to give me a a hand on the Regex?

The rule would be:

  • return everything right of the last / left of the last .

    www.domain.com/images/image.hires.jpg

  • if no . is found, return the full base name www.domain.com/images/image_hi_res

I have a clumsy /\/[^.]+\.[^.]+$/ but don't know how to make the / and the . optional and how to seek for the last . only.

Cheers folks for all the great input, as always. I chose the one Regex that worked for me out of the box.

like image 355
Pekka Avatar asked Jan 02 '10 13:01

Pekka


People also ask

How do I find base URL?

To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.

How do I find the hostname of a URL?

The getHost() method of URL class returns the hostname of the URL. This method will return the IPv6 address enclosed in square brackets ('['and']').

How do you check if a string is a URL in JavaScript?

HTMLInputElement. checkValidity() method is used to check if a string in <input> element's value attribute is URL . The checkvalidity() method returns true if the value is a proper URL and false if the input is not a proper URL.


1 Answers

Yet another solution:

url.replace(/^.*\/|\.[^.]*$/g, '')
like image 189
Christoph Avatar answered Sep 27 '22 20:09

Christoph