Check if a JavaScript string is a URL

前端 未结 30 3448
野趣味
野趣味 2020-11-22 15:41

Is there a way in JavaScript to check if a string is a URL?

RegExes are excluded because the URL is most likely written like stackoverflow; that is to s

30条回答
  •  Happy的楠姐
    2020-11-22 16:22

    Improvement on the accepted answer...

    • Check for ftp/ftps as protocol
    • Has double escaping for backslashes (\\)
    • Ensures that domains have a dot and an extension (.com .io .xyz)
    • Allows full colon (:) in the path e.g. http://thingiverse.com/download:1894343
    • Allows ampersand (&) in path e.g http://en.wikipedia.org/wiki/Procter_&_Gamble
    • Allows @ symbol in path e.g. https://medium.com/@techytimo

      isURL(str) {
        var pattern = new RegExp('^((ft|htt)ps?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?'+ // port
        '(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
        '(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
        return pattern.test(str);
      }
      

提交回复
热议问题