【问题标题】:How to get the filetype of an url string inside a javascript function?如何在 javascript 函数中获取 url 字符串的文件类型?
【发布时间】:2011-03-10 03:08:16
【问题描述】:

我有两种初始化方法:initXML(url)initJSON(url),它们接受一个 url 参数。参数必须是指向 XML 或 JSON 文件的 url 字符串,具体取决于函数。

我想要做的是只有一个名为init(url) 的方法接受一个url 参数,然后根据url 参数字符串的文件类型调用initXML()initJSON()

例如如果 url 参数类似于 'content/file.json' 调用 initJSON(),如果是 'other/file.xml' 调用 initXML(),如果另一个文件类型返回错误。

我怎么知道这个?

提前致谢。

【问题讨论】:

    标签: javascript xml json


    【解决方案1】:

    使用String.match()

    function init(url)
    {
        if ( url.match(/\.json$/i) )
        {
            initJSON(); 
        }
        else if ( url.match(/\.xml$/i) )
        {
            initXML();
        }
        else
        {
            throw "Unknown file type";
        }
    }
    

    【讨论】:

      【解决方案2】:

      一个非常快速的方法是假设你的 URL 中唯一的句点在最后,就在文件类型之前:

      var type = url.split('.');
      type = type[1];
      

      那么type 变量将是'json''xml'

      更简单的系统是使用正则表达式:

      var type = /\.(xml|json)$/.exec(url);
      type = type[1];
      

      【讨论】:

        【解决方案3】:

        你可以使用这样的正则表达式:

        var isJSON = /\.json$/i;
        var isXML = /\.xml$/i;
        if( isJSON.test( url ) == true )
          initJSON()
        else if( isXML.test( url ) == true )
          initXML()
        else
          return( 'error' );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-24
          • 2012-02-11
          • 1970-01-01
          • 1970-01-01
          • 2012-08-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多