网上搜到的匹配网址的正则表达式基本都只能匹配http等前缀开头的url,如果写一级域名比如wurenzhi.com,就会匹配失败,找来找去找不到合适的,自己写吧.
"(^(((https|http|ftp|file|rtsp|mms)://)|www\\.)([a-zA-Z0-9\-]))|^localhost|^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}|(([a-zA-Z0-9])(\\.(com|cn|io|html|htm|top|ltd|net|xin|vip|store|shop|wang|cloud|xyz|ren|tech|online|site|ink|link|love|art|fun|club|cc|website|press|space|beer|luxe|video|group|fit|yoga|net|org|pro|biz|info|design|work|mobi|kim|pub|org|name|tv|co|asia|red|live|wiki|gov|cn|life|world|run|show|city|gold|today|plus|cool|icu|中国|网店|中文网|公司|网络|集团|商城|招聘|佛山|广东|网址|在线|我爱你|商标|餐厅))(:[0-9]{1,4})?(/?))$"
这个正则可以匹配http,www等前缀开头的或者以.com,.cn等后缀结尾的网址,我把阿里云能注册的域名后缀全给粘过来了,如果有未收录的,自己加上就好.
匹配规则主要是给自己手输入网址用的,因为手输时不想加http或www,如果复制了一个网址,你又把http和www删掉了,后面还挂了一大堆参数,那肯定匹配不成功
下面是一个简单的测试demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>正则表达式判断网址</title>
</head>
<body>
<input type="text" id="i1" value="http://wurenzhi.com">
<input type="text" id="i2" placeholder="会在此处显示true或false">
</body>
<script>
i1.oninput = function () {
var myRegExp = new RegExp( //这是正则表达式
"(^(((https|http|ftp|file|rtsp|mms)://)|www\\.)([a-zA-Z0-9\-]))|^localhost|^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}|(([a-zA-Z0-9])(\\.(com|cn|io|html|htm|top|ltd|net|xin|vip|store|shop|wang|cloud|xyz|ren|tech|online|site|ink|link|love|art|fun|club|cc|website|press|space|beer|luxe|video|group|fit|yoga|net|org|pro|biz|info|design|work|mobi|kim|pub|org|name|tv|co|asia|red|live|wiki|gov|cn|life|world|run|show|city|gold|today|plus|cool|icu|中国|网店|中文网|公司|网络|集团|商城|招聘|佛山|广东|网址|在线|我爱你|商标|餐厅))(:[0-9]{1,4})?(/?))$"
)
i2.value = myRegExp.test(i1.value) //通过test()得到测试结果,然后赋值给输入框i2,i2可以看到结果true或者false
}
</script>
</html>