Javascript 如何使用javascript从url字符串中提取url文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6997262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:12:17  来源:igfitidea点击:

How to pull url file extension out of url string using javascript

javascriptfileurl

提问by Carl

How do I find the file extension of a URL using javascript? example URL:

如何使用 javascript 查找 URL 的文件扩展名?示例网址:

http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294

I just want the 'swf' of the entire URL. I need it to find the extension if the url was also in the following format

我只想要整个 URL 的“swf”。如果 url 也是以下格式,我需要它来查找扩展名

http://www.adobe.com/products/flashplayer/include/marquee/design.swf

Obviously this URL does not have the parameters behind it.

显然这个 URL 后面没有参数。

Anybody know?

有人知道吗?

Thanks in advance

提前致谢

回答by iConnor

Something like this maybe?

也许像这样的东西?

var fileName = 'http://localhost/assets/images/main.jpg';

var extension = fileName.split('.').pop(); 

console.log(extension, extension === 'jpg');

The result you see in the console is.

您在控制台中看到的结果是。

jpg true

if for some reason you have a url like this something.jpg?name=blahor something.jpg#blahthen you could do

如果由于某种原因你有这样的网址,something.jpg?name=blah或者something.jpg#blah你可以这样做

extension = extension.split(/\#|\?/g)[0];

drop in

下车

var fileExtension = function( url ) {
    return url.split('.').pop().split(/\#|\?/)[0];
}

回答by T.Todua

function get_url_extension( url ) {
    return url.split(/[#?]/)[0].split('.').pop().trim();
}

example:

例子:

get_url_extension('https://example.com/folder/file.jpg');
get_url_extension('https://example.com/fold.er/fil.e.jpg?param.eter#hash=12.345');

outputs ------> jpg

输出------> jpg

回答by Alex K.

For the extension you could use this function:

对于扩展,您可以使用此功能:

function ext(url) {
    // Remove everything to the last slash in URL
    url = url.substr(1 + url.lastIndexOf("/"));

    // Break URL at ? and take first part (file name, extension)
    url = url.split('?')[0];

    // Sometimes URL doesn't have ? but #, so we should aslo do the same for #
    url = url.split('#')[0];

    // Now we have only extension
    return url;
}

Or shorter:

或更短:

function ext(url) {
    return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('#')[0].substr(url.lastIndexOf("."))
}

Examples:

例子:

ext("design.swf")
ext("/design.swf")
ext("http://www.adobe.com/products/flashplayer/include/marquee/design.swf")
ext("/marquee/design.swf?width=792&height=294")
ext("design.swf?f=aa.bb")
ext("../?design.swf?width=792&height=294&.XXX")
ext("http://www.example.com/some/page.html#fragment1")
ext("http://www.example.com/some/dynamic.php?foo=bar#fragment1")

Note: File extension is provided with dot (.) at the beginning. So if result.charat(0) != "."there is no extension.

注意:文件扩展名以点 ( .) 开头。所以如果result.charat(0) != "."没有扩展。

回答by Adam

This is the answer:

这是答案:

var extension = path.match(/\.([^\./\?]+)($|\?)/)[1];

回答by Federico Lebrón

Take a look at regular expressions. Specifically, something like /([^.]+.[^?])\?/.

看看正则表达式。具体来说,像/([^.]+.[^?])\?/.

回答by Yuval A.

  // Gets file extension from URL, or return false if there's no extension
  function getExtension(url) {
      // Extension starts after the first dot after the last slash
      var extStart = url.indexOf('.',url.lastIndexOf('/')+1);
      if (extStart==-1) return false;
      var ext = url.substr(extStart+1),
          // end of extension must be one of: end-of-string or question-mark or hash-mark
          extEnd = ext.search(/$|[?#]/);
      return ext.substring (0,extEnd);
  }

回答by OZZIE

url.split('?')[0].split('.').pop()

usually #hash is not part of the url but treated separately

通常#hash 不是 url 的一部分,而是单独处理

回答by svarog

You can use the (relatively) new URLobject to help you parse your url. The property pathnameis especially useful because it returns the url path without the hostname and parameters.

您可以使用(相对)新URL对象来帮助您解析您的 url。该属性pathname特别有用,因为它返回没有主机名和参数的 url 路径。

let url = new URL('http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294');
// the .pathname method returns the path
url.pathname; // returns "/products/flashplayer/include/marquee/design.swf"
// now get the file name
let filename = url.pathname.split('/').reverse()[0]
// returns "design.swf"
let ext = filename.split('.')[1];
// returns 'swf'

回答by gzzz

function ext(url){
    var ext = url.substr(url.lastIndexOf('/') + 1),
        ext = ext.split('?')[0],
        ext = ext.split('#')[0],
        dot = ext.lastIndexOf('.');

    return dot > -1 ? ext.substring(dot + 1) : '';
}

回答by ek_ny

    var doc = document.location.toString().substring(document.location.toString().lastIndexOf("/"))
    alert(doc.substring(doc.lastIndexOf(".")))