我需要确保捕获没有有效方案的 url,并在它们前面添加一个 http://
。
我知道我可以在变量中搜索 http://
。但是,如果有一些工具可以正确检查有效方案,那将是更好的做法。有没有办法检查有效方案?
var a = "www.example.com";
最佳答案
由于您所显示的是一个完全有效的相对 URL,所以这很复杂。区分相对 URL 和损坏的绝对 URL 必然涉及一些猜测。
如果您知道您不是在处理相对 URL,那么根据定义,我们正在处理应该有方案的链接,因此我们可以寻找没有的链接。如果我们引用RFC-3986 §3我们看到该方案通过 :
:
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/