-2

i'm working on a project and depending on what variables i send to a server file there can be different responses. one of them is a link and i want to check with jquery if the response is a link so i can redirect it..

i googled a bit and could only find how to redirect with jquery and this is not what i need.

this is my code at the moment and i need to find something for the response.message == URL

    if(response.message == URL){
        window.location.href = response.url;
    }else{
       $('#errormsg').html('<div class="alert alert-success">'+
       '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'
                            +response.message+'</div>');
    }

So does anyone know of a method to check if a string is an url? i would greatly appreciate your help :)

Sjoerd de Wit
  • 2,353
  • 5
  • 26
  • 45
  • 1
    Please show the rendered html for the case of link of response.message – Bhojendra Rauniyar Jun 10 '14 at 09:34
  • 1
    You could perhaps use regular expression matching to see if the response message approximates the format of a URL. Or maybe even just check if it starts with http? (Overly-simplistic, I know, but it depends on what other kinds of response messages you would expect.) Does the client-side code have any way of knowing that it *should* expect a URL (or any different response) based on the data it's sending to the server in the first place? – David Jun 10 '14 at 09:35
  • 1
    Already asked many time: http://stackoverflow.com/questions/1701898/how-to-detect-whether-a-string-is-in-url-format-using-javascript – justtal Jun 10 '14 at 09:39

1 Answers1

1

It looks like you need a regular expression to match a URL. Looking here, you can find a suitable regex, which you can use as follows:

regex = new RegExp("#^((?#
    the scheme:
  )(?:https?://)(?#
    second level domains and beyond:
  )(?:[\S]+\.)+((?#
    top level domains:
  )MUSEUM|TRAVEL|AERO|ARPA|ASIA|EDU|GOV|MIL|MOBI|(?#
  )COOP|INFO|NAME|BIZ|CAT|COM|INT|JOBS|NET|ORG|PRO|TEL|(?#
  )A[CDEFGILMNOQRSTUWXZ]|B[ABDEFGHIJLMNORSTVWYZ]|(?#
  )C[ACDFGHIKLMNORUVXYZ]|D[EJKMOZ]|(?#
  )E[CEGHRSTU]|F[IJKMOR]|G[ABDEFGHILMNPQRSTUWY]|(?#
  )H[KMNRTU]|I[DELMNOQRST]|J[EMOP]|(?#
  )K[EGHIMNPRWYZ]|L[ABCIKRSTUVY]|M[ACDEFGHKLMNOPQRSTUVWXYZ]|(?#
  )N[ACEFGILOPRUZ]|OM|P[AEFGHKLMNRSTWY]|QA|R[EOSUW]|(?#
  )S[ABCDEGHIJKLMNORTUVYZ]|T[CDFGHJKLMNOPRTVWZ]|(?#
  )U[AGKMSYZ]|V[ACEGINU]|W[FS]|Y[ETU]|Z[AMW])(?#
    the path, can be there or not:
  )(/[a-z0-9\._/~%\-\+&\#\?!=\(\)@]*)?)$#i")

if (response.message.match(regex)) {
  ...
} else {
  ...
}
Community
  • 1
  • 1
Graham Kaemmer
  • 315
  • 1
  • 8