Check if a JavaScript string is a URL

前端 未结 30 2916
野趣味
野趣味 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条回答
  •  遇见更好的自我
    2020-11-22 16:38

    This function disallows localhost and only allows URLs for web pages (ie, only allows http or https protocol).

    It also only allows safe characters as defined here: https://www.urlencoder.io/learn/

    function isValidWebUrl(url) {
       let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
       return regEx.test(url);
    }
    

提交回复
热议问题