如果 URL 是 Javascript 或 jQuery 中的相对路径或绝对路径,如何测试它?我想根据传入的 URL 是本地路径还是外部路径进行相应处理。
if (urlString starts with http:// or https://)
//do this
FAST
如果您只需要测试http://
or https://
那么最有效率的 way is:
if (urlString.indexOf('http://') === 0 || urlString.indexOf('https://') === 0)
普遍的
不过,我建议一个更通用、不区分大小写、与协议无关方法:
var r = new RegExp('^(?:[a-z+]+:)?//', 'i');
r.test('http://example.com'); // true - regular http absolute URL
r.test('HTTP://EXAMPLE.COM'); // true - HTTP upper-case absolute URL
r.test('https://www.exmaple.com'); // true - secure http absolute URL
r.test('ftp://example.com/file.txt'); // true - file transfer absolute URL
r.test('//cdn.example.com/lib.js'); // true - protocol-relative absolute URL
r.test('git+ssh://example.con/item'); // true - absolute URL with '+' in scheme
r.test('/myfolder/test.txt'); // false - relative URL
r.test('test'); // false - also relative URL
解释正则表达式
^(?:[a-z+]+:)?//
^
- 字符串的开头
(?:
- 非捕获组的开始
[a-z+]+
- 'a' 到 'z' 或“+”中的任何字符 1 次或多次
:
- 字符串(冒号字符)
)?
- 非捕获组的末尾。组出现 0 或 1 次
//
- 字符串(两个正斜杠字符)
'i'
- 不区分大小写的标志
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)