4

I am trying to get a simple regex to verify that a URL contains the ending figures

var testRegex = /^https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/;
var imageUrl = "http://stackoverflow.com/questions/406192/how-to-get-the-current-url-in-jquery";
if (testRegex.test(imageUrl)) {
  alert('Not Match');
}

And this should trigger alert('Not Match'); and it doesn't ? See http://jsfiddle.net/UgfKn/

What's going on ?

Andy
  • 18,723
  • 12
  • 46
  • 54

3 Answers3

3

do you mean:

if (!testRegex.test(imageUrl)) {
  alert('Not Match');
}
itea
  • 444
  • 3
  • 5
  • yeah haha stupid error by me :) - does the regex look OK at least for image url's ? – Andy Jan 12 '12 at 12:13
  • append lower-case i after the regular expression: `/^https?:\/\/(?:[a-z\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png)$/i`, in case of upper-case characters. – itea Jan 12 '12 at 12:20
  • 2
    In case someone else finds this answer in a while, the regex provided doesn't support numbers in urls (I also added BMP support), so the modified version is : `/^https?:\/\/(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:\/[^\/#?]+)+\.(?:jpe?g|gif|png|bmp)$/i` – Bun Jan 03 '14 at 02:29
1

testRegex.test will evaluate to True if testRegex DOES match. ie

if (testRegex.test(imageUrl)) {
  alert('Match');
} else {
  alert('Not match');
}
mathematical.coffee
  • 55,977
  • 11
  • 154
  • 194
0

You are missing ! in the if condition

if ( ! testRegex.test(imageUrl1) ) {
    alert('Not Match');
}

See http://jsfiddle.net/UgfKn/1/

Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82