user3105607
user3105607

Reputation: 369

Requiring a particular file extension in javascript regex

I'm using this reg ex

var regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;

This is used on a field for specifying image urls, so I need the last part of the url to be either .jpg, .png, .gif etc

How can i modify the regex to test this?

Thanks

(regex used: http://blog.mattheworiordan.com/post/13174566389/url-regular-expression-for-links-with-or-without-the)

Upvotes: 0

Views: 230

Answers (1)

Michael Tang
Michael Tang

Reputation: 4896

Try appending your existing regex with \.(jpg|png|gif)

Basically what this does is it checks for a dot (\., must be escaped since its a special character), then checks if a string is followed by either jpg, png, or gif.

Debuggex is a wonderful tool to play around with (I learned regex messing with it).

((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)\.(jpg|png|gif)

Regular expression visualization

Debuggex Demo

Upvotes: 1

Related Questions