我想测试我的网址有效性,它应该以http://或https://开头,
我使用过这个RegExp:
private testIfValidURL(str){ const pattern = new RegExp(‘^(https?:\ / \ /)?’+ //协议…
只是改变 ^(https?:\\/\\/)?' 至 ^(https?:\\/\\/)' , ? 表示您想要匹配模式的零个或一个匹配项。你实际上只想要一次出现,所以不要使用 ? :)
^(https?:\\/\\/)?'
^(https?:\\/\\/)'
?
从 常用表达 :
? - 使前面的项目可选。贪心,所以如果可能的话,可选项包含在比赛中。
你可以删除 (...)? 字符,因此必须首先使用http或https序列。
(...)?
function testIfValidURL(str) { const 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 locator return !!pattern.test(str); } console.log(testIfValidURL('www.abcd.com')); console.log(testIfValidURL('http://www.abcd.com')); console.log(testIfValidURL('https://www.abcd.com')); console.log(testIfValidURL('htt://www.abcd.com'));