JS 正则表达式仅排除 http - 必须包含 https

JS regex exclude http only - https must be included

我需要使用 Javascript 来验证 URL 输入,其中除了不安全的 http 协议之外的所有 URL 都是有效的。

有效 URL 示例:

https://example.com/
https://example.com/path
application://example.com/path
application://example

无效示例URL:

http:\example.com

我试过负前瞻,但它不起作用:

^(?!http[s]{0}).*:\/\/.*$

如何编写正则表达式,只排除 http 协议(必须包括其他协议,例如 https)?

你可以这样使用它:

^(?!http:)[^:]+:\/\/.+$

(?!http:) 是否定前瞻,如果字符串以 http: 开头,则匹配失败,因此 http://... URLs.

的匹配失败

但是请注意,此正则表达式不会进行复杂的 URL 验证,它只会处理 http: URLs/

的匹配失败

您可以使用 URL api 并将 protocol 属性 与 http:

匹配

let urlTester = (url) => {
  let urlParsed = new URL(url)
  return urlParsed.protocol !== 'http:'
}

console.log(urlTester('https://example.com/'))
console.log(urlTester('https://example.com/path'))
console.log(urlTester('application://example.com/path'))
console.log(urlTester('application://example'))
console.log(urlTester('http://example.com'))