如果 URL 是 Javascript 或 jQuery 中的相对路径或绝对路径,我该如何测试它?我想根据传入的 URL 是本地路径还是外部路径进行相应处理。
if (urlString starts with http:// or https://)
//do this
最佳答案
快速
如果您只需要测试 http://
或 https://
那么最有效的方法是:
if (urlString.indexOf('http://') === 0 || urlString.indexOf('https://') === 0)
通用
但是,我建议使用一种更通用、不区分大小写、与协议(protocol)无关的方法:
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'
- 不区分大小写的标志
关于javascript - 如何测试 URL 字符串是绝对的还是相对的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10687099/