Piyush Chauhan
Piyush Chauhan

Reputation: 1543

Image URL javascript regular expression to accommodate for special urls

I have an image url regular expression which is being used to validate a image on the form using ng-pattern directive.

Currently I'm struggling to accomodate for cases like https://google.com.png. Any help would be really appreciated.

Regex:

'^((?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?)\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF)$'

Better to view here:

https://regex101.com/r/dH1wT6/1

Upvotes: 0

Views: 230

Answers (1)

LukStorms
LukStorms

Reputation: 29647

Simplifying the regex :

^(?!mailto)(?:https?|ftp):\/(?:\/?(?:[.#@?=]?[a-z0-9\u00a1-\uffff]+)+)+[.]?(?:png|jpe?g|gif)$

Need to use the i flag for this to make the search not case sensitive.

But you should verify with your list of url's if this allows to much or to little.

Can test it here

If you put the regex in a javascript string, don't forget that you need to backslash the backslashes.

Upvotes: 1

Related Questions