检查JavaScript字符串是否为URL [英] Check if a JavaScript string is a URL

查看:135
本文介绍了检查JavaScript字符串是否为URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中是否有办法检查字符串是否为URL?

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

排除RegExes,因为URL最有可能写成计算器;也就是说它可能没有 .com www http

RegExes are excluded because the URL is most likely written like stackoverflow; that is to say that it might not have a .com, www or http.

推荐答案

带答案的相关问题:

Javascript正则表达式网址匹配

或者来自 Devshed

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
    '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
    '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
    '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
    '(\?[;&a-z\d%_.~+=-]*)?'+ // query string
    '(\#[-a-z\d_]*)?$','i'); // fragment locater
  if(!pattern.test(str)) {
    alert("Please enter a valid URL.");
    return false;
  } else {
    return true;
  }
}

这篇关于检查JavaScript字符串是否为URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆