确定string是否是对本地或外部文件的引用

时间:2017-02-19 22:47:55

标签: javascript

如何确定字符串是本地路径还是对其他服务器的引用?

例如,使用以下URL列表,如何确定哪些URL引用本地文件路径或example.com?

var paths = [
    'foo/bar.css',
    '/bar/foo.css',
    '//cdn.example.com/monkey.css',
    'https://example.com/banana.css'
];

我查看了url npm包,但它无法将第三条路径解析为包含主机的对象。

我要做的是使用仅知道页面URL的实用程序从页面以及链接样式表中提取所有CSS信息。我需要知道将后续请求发送到原始主机或其他一些请求,例如example.com

3 个答案:

答案 0 :(得分:1)

一种简单的方法是检查http://http://的字符串。您可以根据需要添加任何其他搜索字符串(ftp://等)

var paths = ['foo/bar.css',
             '/bar/foo.css',
             '//cdn.example.com/monkey.css',
             'https://example.com/banana.css'];
             
paths.forEach(function(url){
  var yesNo = (url.indexOf("http:")=== 0 || 
               url.indexOf("https:") === 0 ||
               url.indexOf("//") === 0 && 
               (window.location.protocol === "http:" || window.location.protocol === "https:")) 
               ? "" : " NOT";
  console.log(url +  " is" + yesNo + " an external path");
});

答案 1 :(得分:1)

要解析引用URI,您需要提供基本URL。只有这样才能完全解释这样的URL。

在您的示例中,这将是:

var url = require("url");
var baseUrl = 'http://www.google.com/thing'; // insert your actual base URL here
var paths = [
    'foo/bar.css',
    '/bar/foo.css',
    '//cdn.example.com/monkey.css',
    'https://example.com/banana.css'
];
paths.forEach((p)=>{
    console.log(url.parse(url.resolve(baseUrl,p)).hostname);
});

答案 2 :(得分:0)

我可能会遍历数组并拥有一组if语句。像这样的东西(不是复制粘贴友好,伪代码)

function checkPath(string) {
    if(string.contains("https://")
    if(string.charArray[0] == "/" && string.charArray[1] == "/")
    if(string.charArray[0] == "/" && !string.charArray[1] == "/")
    if(string.charArray[0] != "/")
}

那些if应该能够将所有这些字符串解析为单独的函数,您可以使用它们来单独处理它们。当你自己从头开始创建函数时,不要使用库。