Javascript 检查 url 中是否没有有效方案

标签 javascript validation url-scheme

我需要确保捕获没有有效方案的 url,并在它们前面添加一个 http://

我知道我可以在变量中搜索 http://。但是,如果有一些工具可以正确检查有效方案,那将是更好的做法。有没有办法检查有效方案?

var a = "www.example.com";

最佳答案

由于您所显示的是一个完全有效的相对 URL,所以这很复杂。区分相对 URL 和损坏的绝对 URL 必然涉及一些猜测。

如果您知道您不是在处理相对 URL,那么根据定义,我们正在处理应该有方案的链接,因此我们可以寻找没有的链接。如果我们引用RFC-3986 §3我们看到该方案通过 ::

与 URL 的其余部分分开
The following are two example URIs and their component parts:

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment
          |   _____________________|__
         / \ /                        \
         urn:example:animal:ferret:nose

...and from §3.1, we can see that schemes are a series of an alpha followed by zero or more alphanums, +, -, or ., seprated from the rest of the URL by a ://:

scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )

So you can tell with a simple regular expression:

if (!/^[a-z][a-z0-9+.\-]*:/i.test(a)) {
    // 'a' doesn't start with a scheme
}

但同样,前提是您不处理相对 URL。

那个正则表达式说:

  • ^ - 输入开始
  • [a-z] - RFC 中通常定义的任何字母字符(例如,英文字母 A 到 Z)
  • [a-z0-9+.\-]* - 任意字母、数字、 的零个或多个(即末尾的 *) +.-.
  • : - 冒号

...i 标志表示“不区分大小写”。

关于Javascript 检查 url 中是否没有有效方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34251135/

相关文章:

javascript - 无法让 JavaScript 密码正则表达式验证生效

php - 当数据验证失败时保留表单字段中的值

ios - 如何从 URL 方案中获取参数。

JavaFX 播放音频时出现问题 : Unsupported protocol "file"

swift - 获取用于启动 OS X 应用程序的初始 URL

javascript - 正则表达式在函数中是如何工作的?

javascript - Angular js - 使用延迟加载从 View 中需要 js 文件

ruby-on-rails - 这种长度验证在 Ruby on Rails 中是如何工作的?

javascript - Mongoose map

javascript - 'this' 在 emberJS 框架中真正代表什么?