Daily-Interview-Question
Daily-Interview-Question copied to clipboard
第174题:如何判断url中只包含qq.com
例如:
http://www.qq.com // 通过
http://www.qq.com.cn // 不通过
http://www.qq.com/a/b // 通过
http://www.qq.com?a=1 // 通过
http://www.123qq.com?a=1 // 不通过
p=/(?<!\w+)qq(?=\.com)[\/|\?]?/g
正则匹配
function check(url){ if(/^(http://[^=]+.qq.com)($|[?/])/.test(url)){ return true; }else{ return false; } }
\/\/w+\.qq\.com[^.]*$
function qqUrl(url) { let reg =/^http(s)?://www.qq.com([/|?].+)?$/ return reg.test(url)?'通过':'不通过' }
var pat = /^http(s)?:\/\/w+\.qq\.com[^.]*$/
location.hostname === 'www.qq.com'
例如:
http://www.qq.com // 通过
http://www.qq.com.cn // 不通过
http://www.qq.com/a/b // 通过
http://www.qq.com?a=1 // 通过
http://www.123qq.com?a=1 // 不通过
解答:正则
function check(url){
if(/\/\/w+\.qq\.com[^.]*$/.test(url)){
return true;
}else{
return false;
}
}
check('http://www.qq.com')
// true
check('http://www.qq.com.cn')
// false
check('http://www.qq.com/a/b')
// true
check('http://www.qq.com?a=1')
// true
check('http://www.123qq.com?a=1')
// false
这个正则很简单,包含 .qq.com 就可以,但是有一种情况,如果域名不是包含 qq.com 而仅仅是参数后面包含了 qq.com 怎么办?例如 http://www.baidu.com?redirect=http://www.qq.com/a
check('http://www.baidu.com?redirect=http://www.qq.com/a')
// true
如何排除这种情况?
function check(url){
if(/^https?:\/\/w+\.qq\.com[^.]*$/.test(url)){
return true;
}else{
return false;
}
}
check('http://www.qq.com')
// true
check('http://www.qq.com.cn')
// false
check('http://www.qq.com/a/b')
// true
check('http://www.qq.com?a=1')
// true
check('http://www.123qq.com?a=1')
// false
check('http://www.baidu.com?redirect=http://www.qq.com/a')
// true
若有收获,就点个赞吧
避免是参数中的qq.com,其实就是要qq.com匹配前没有?,所以从开头开始到qq.com处,没有?出现即可;结尾时,不能是.避免域名还未结束
const check = (value) => /^[^\?]+\.qq\.com[^.]*$/.test(value);
check('http://www.qq.com')
// true
check('http://www.qq.com.cn')
// false
check('http://www.qq.com/a/b')
// true
check('http://www.qq.com?a=1')
// true
check('http://www.123qq.com?a=1')
// false
check('http://www.baidu.com?redirect=http://www.qq.com/a')
// false
check('http://www.qq.com?redirect=http://www.music.qq.com/a/b')
// true
若有收获,就点个赞吧
这道题的前提必须是输入合法的url
const checkUrlReg = /^http[s]?\:\/\/www\.qq\.com[\/\?]?[^.].*?[\.]?.*$/
new URL('https://www.qq.com/a/b?c=1').host==='www.qq.com'
const cases = [
'http://www.qq.com', // 通过
'http://www.qq.com.cn', // 不通过
'http://www.qq.com/a/b', // 通过
'http://www.qq.com?a=1', // 通过
'http://www.123qq.com?a=1', // 不通过
'http://www.baidu.com?redirect=http://www.qq.com/a', // 不通过
'http://www.qq.com?redirect=http://www.music.qq.com/a/b', // 通过
'https://qq.com', // 通过
'https://qq.com#a', // 通过
'不合法的url', // @wozien 不通过
]
const reg = /^https?:\/\/(\w+\.)?qq\.com([/?#]|$)/
const check = url => reg.test(url)
cases.map(check) // [true, false, true, true, false, false, true, true, true, false]
正则结尾处:([/?#]|$),如果以前面域名结尾,后续只能跟 路径(/)、参数(?)、哈希(#),要么就直接结结尾($)。