English 中文(简体)
j) 从尿液中获取姓名的职能
原标题:js function to get filename from url

http://www.example.com/blah/th.html” http://www.example.com/blah/th.html。

我需要一种 j印功能,给我留下这种价值。

我的所有王位都采用相同的格式(2封信标,延长日期:html)。

我希望它是一种安全的职能,这样,如果有人用空洞的ur子走,那就不了。

我知道如何检查时间长,但我应该检查一下谁是谁?

最佳回答
var filename = url.split( / ).pop()
问题回答

为什么如此困难?

= url.split( # )[0].split( ? )[0].split( / ).pop();

下面的登记结果与上述通常相同,但如果URL明显畸形,则会退回空洞。

= (url.match(/^w+:(/+([^/#?s]+)){2,}(#|?|$)/)||[])[2]||  ;
// Returns empty string for relative URLs unlike the original approach

= (url.match(/^w+:(/+([^/#?s]+)){2,}/)||[])[2]||  ;
// Ignores trailing slash (e.g., ".../posts/?a#b" results "posts")

这三个国家将返回<代码>. ?

  • my://host/path=&%dir///file?.name?q=1/2&3=&#a/?b//?

第三种办法还将从下列地点退回<代码>dir. 姓名:

  • my://host/path=&%dir///dir.name/?not/these/#/ones//?

First Edit (Sep 2023) :

  • Changed processing order because RFC 3986 explicitly allows fragments to having unencoded slashes. Now it would handles fine even the query("search" in JS) includes unencoded slashes(which obviously had to be encoded).
  • This means it might properly handles any form of URLs that most browsers could recognize.
  • Using RegEx method was added which includes very basic validity test. Similar concept to the original one but using different approach.

测试your URL,加入如下。 第三个问题将忽视上述法典描述的拖拉。 请评论RegEx公司是否适当处理任何有效的URL

<style>*{margin:0;padding:0;box-sizing:border-box;border:none;}label{font-size:90%}input{display:block;margin:.2em auto 0;padding:.8em 1.2em;width:calc(100% - 5px);background:#f8f8f8;border-radius:1em;}p{margin-top:1.4em;padding-left:.5em;font-size:95%;color:#0008}p::after{content:attr(title);margin-left:.5em;padding:.4em .2em;background:#fe8;border-radius:.5em;font-weight:800;color:#000;}</style>
<label for="input">Enter your URL here:</label>
<input value="my://host/path=&%dir///file?.name?q=1/2&3=&#a/?b//?" id="input">
<p>A</p>
<p>B</p>
<p>C</p>
<script>
((input = document.querySelector( input ), output = document.querySelectorAll( p )) => {
  const getFilename = _=> {
    output[0].title = input.value.split( # )[0].split( ? )[0].split( / ).pop();
    output[1].title = (input.value.match(/^w+:(/+([^/#?s]+)){2,}(#|?|$)/)||[])[2]||  ;
    output[2].title = (input.value.match(/^w+:(/+([^/#?s]+)){2,}/)||[])[2]||  ;
  };
  getFilename();
  input.addEventListener( input , getFilename);
  input.select();
})();
</script>

使用配对功能。

function GetFilename(url)
{
   if (url)
   {
      var m = url.toString().match(/.*/(.+?)./);
      if (m && m.length > 1)
      {
         return m[1];
      }
   }
   return "";
}

Similar to the others, but...I ve used Tom s simple script - a single line,
then you can use the filename var anywhere:
http://www.tomhoppe.com/index.php/2008/02/grab-filename-from-window-location/

var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1);

除现有答复外,我建议使用URL() 构造/code>。 (browsers and Node.js) 因为你可以肯定你的URL是有效的:

const url =  https://test.com/path/photo123.png?param1=1&param2=2#hash ;

let filename =   ;
try {
  filename = new URL(url).pathname.split( / ).pop();
} catch (e) {
  console.error(e);
}
console.log(`filename: ${filename}`);

这应当适用于所有案件。

function getFilenameFromUrl(url) {
  const pathname = new URL(url).pathname;
  const index = pathname.lastIndexOf( / );
  return pathname.substring(index + 1) // if index === -1 then index+1 will be 0
}

用于URL查询和洗衣识别剂的常规解决办法:

function fileNameFromUrl(url) {
   var matches = url.match(//([^/?#]+)[^/]*$/);
   if (matches.length > 1) {
     return matches[1];
   }
   return null;
}

JSFiddle here

由于案件往往与海关编码不一致,因此,I考察了Javad 字典:URL。 Alas, It chokes on relative URLs! 而且,它没有获得档案名称的财产。 Noc.

<<>has>/em> 是解决这一共同问题的良好图书馆。 Behold URI.js。 你们所需要的是一份简单的声明,如:

let file = new URI(url).filename()

这样,我们就能够形成一种简单的职能,从而取消检查,并取消档案延期:

function fileName(url) {
   if (url === null || typeof url ===  undefined )
      return   
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf( . )) // Remove the extension
}

这里有一刀子,有测试案例可以与周围一起进行。 除驾驶路线外,所有案件都通过。

test( Dots in file name without URL ,  dotted.file.name.png ,  dotted.file.name )
test( Dots in file name with URL ,  http://example.com/file.name.txt ,  file.name )
test( Lengthy URL with parameters ,  /my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo ,  filename )
test( URL with hash ,  /my/folder/filename.html#dssddsdsd ,  filename )
test( URL with query strings ,  /my/folder/filename.html?toto=33&dududu=podpodp ,  filename )
test( Hash after query string ,  http://www.myblog.com/filename.php?year=2019#06 ,  filename )
 test( Query parameter with file path character ,  http://www.example.com/filename.zip?passkey=1/2 ,  filename )
test( Query parameter with file path character and hash ,  http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top ,  filename )
test( Asian characters ,  http://example.com/文件名.html ,  文件名 )
test( URL without file name ,  http://www.example.com ,   )
test( Null , null,   )
test( Undefined , undefined,   )
test( Empty string ,   ,   )
test( Drive path name ,  C:/fakepath/filename.csv ,  filename )

function fileName(url) {
   if (url === null || typeof url ===  undefined )
      return   
   let file = new URI(url).filename() // File name with file extension
   return file.substring(0, file.lastIndexOf( . )) // Remove the extension
}

function test(description, input, expected) {
   let result = fileName(input)
   let pass =  FAIL 
   if (result === expected)
      pass =  PASS 
   console.log(pass +  :   + description +  :   + input)
   console.log(   =>  "  + fileName(input) +  " )
}
<script src="https://cdn.jsdelivr.net/gh/medialize/URI.js@master/src/URI.js"></script>

<

PASS: Dots in file name without URL: dotted.file.name.png
  =>  "dotted.file.name"
PASS: Dots in file name with URL: http://example.com/file.name.txt
  =>  "file.name"
PASS: Lengthy URL with parameters: /my/folder/filename.html#dssddsdsd?toto=33&dududu=podpodpo
  =>  "filename"
PASS: URL with hash: /my/folder/filename.html#dssddsdsd
  =>  "filename"
PASS: URL with query strings: /my/folder/filename.html?toto=33&dududu=podpodp
  =>  "filename"
PASS: Hash after query string: http://www.myblog.com/filename.php?year=2019#06
  =>  "filename"
PASS: Query parameter with file path character: http://www.example.com/filename.zip?passkey=1/2
  =>  "filename"
PASS: Query parameter with file path character and hash: http://www.example.com/filename.html?lang=en&user=Aan9u/o8ai#top
  =>  "filename"
PASS: Asian characters: http://example.com/文件名.html
  =>  "文件名"
PASS: URL without file name: http://www.example.com
  =>  ""
PASS: Null: null
  =>  ""
PASS: Undefined: undefined
  =>  ""
PASS: Empty string: 
  =>  ""
FAIL: Drive path name: C:/fakepath/filename.csv
  =>  ""

这一解决办法是,如果你重心写习俗法典,不要使用图书馆为你工作,那么你会这样做。 如果你想要找到解决办法,那是 t的。

those will not work for lenghty url like
"/my/folder/questions.html#dssddsdsd?toto=33&dududu=podpodpo"

here I expect to get "questions.html". So a possible (slow) solution is as below

fname=function(url) 
{ return url?url.split( / ).pop().split( # ).shift().split( ? ).shift():null }

那么,你就可以检验,在任何情况下,你只能获得档案名称。

fname("/my/folder/questions.html#dssddsdsd?toto=33&dududu=podpodpo")
-->"questions.html"
fname("/my/folder/questions.html#dssddsdsd")
-->"questions.html"
fname("/my/folder/questions.html?toto=33&dududu=podpodpo")
"-->questions.html"

(and it works for null)

(I would love to see a faster or smarter solution)

这只是在浏览器环境中工作。 不适合噪音。

function getFilename(url) {
  const filename = decodeURIComponent(new URL(url).pathname.split( / ).pop());
  if (!filename) return  index.html ; // some default filename
  return filename;
}

function filenameWithoutExtension(filename) {
  return filename.replace(/^(.+?)(?:.[^.]*)?$/,  $1 );
}

这里有两个职能:

  • first one get filename from url
  • second one get filename without extension from a full filename

对URL进行校服时,最好选择新的<代码>URL。 并且注意到URL并不总是包含档案名称。

Notice: This function try to resolve filename from an URL. But it do NOT guarantee that the filename is valid and suitable for use:

  • Some OS disallow certain character in filename (e.g. : in windows, in most OS, ...);
  • Some filename may reserved by OS (e.g. CON in windows);
  • Some filename may make user unhappy to handle it (e.g. a file named "--help" in Linux)

试验:

function getFilename(url) {
  const filename = decodeURIComponent(new URL(url).pathname.split( / ).pop());
  if (!filename) return  index.html ; // some default filename
  return filename;
}

function test(url) {
  console.log( Filename: %o
Url: %o , getFilename(url), url);
}

test( http://www.example.com );
test( http://www.example.com/ );
test( http://www.example.com/name.txt );
test( http://www.example.com/path/name.txt );
test( http://www.example.com/path/name.txt/realname.txt );
test( http://www.example.com/page.html#!/home );
test( http://www.example.com/page.html?lang=en&user=Aan9u/o8ai#top );
test( http://www.example.com/%E6%96%87%E4%BB%B6%E5%90%8D.txt )

缩略语 这将允许在上面注明期限的档案名称,例如<编码>http://example.com/file.name.txt。 与提供<代码>的公认答案不同。

function GetFilename(url)
{
    if (url)
    {
        return url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
    }
    return "";
}

This should handle anything you throw at it (absolute URLs, relative URLs, complex AWS URLs, etc). It includes an optional default or uses a psuedorandom string if neither a filename nor a default were present.

function parseUrlFilename(url, defaultFilename = null) {
    let filename = new URL(url, "https://example.com").href.split("#").shift().split("?").shift().split("/").pop(); //No need to change "https://example.com"; it s only present to allow for processing relative URLs.
    if(!filename) {
        if(defaultFilename) {
            filename = defaultFilename;
        //No default filename provided; use a pseudorandom string.
        } else {
            filename = Math.random().toString(36).substr(2, 10);
        }
    }
    
    return filename;
}

Props to @hayatbiralem for nailing the order of the split(s

http://projects.allmarkedup.com/jquery_url_parser/“rel=“nofollow noreferer”>URL plugin:

var file = jQuery.url.attr("file");
var fileNoExt = file.replace(/.(html|htm)$/, "");
// file == "th.html", fileNoExt = "th"

no子和浏览器,根据@pauls的回答,但用洗衣和防御工事解决问题:

export function getFileNameFromUrl(url) {
  const hashIndex = url.indexOf( # )
  url = hashIndex !== -1 ? url.substring(0, hashIndex) : url
  return (url.split( / ).pop() ||   ).replace(/[?].*$/g,   )
} 

几乎没有案件:

describe( getFileNameFromUrl , () => {

  it( absolute, hash and no extension , () => {
    expect(getFileNameFromUrl(
       https://foo.bar/qs/bar/js-function-to-get-filename-from-url#comment95124061_53560218 ))
    .toBe( js-function-to-get-filename-from-url )
  })

  it( relative, extension and parameters , () => {
    expect(getFileNameFromUrl( ../foo.png?ar=8 )).toBe( foo.png )
  })

  it( file name with multiple dots, hash with slash , () => {
    expect(getFileNameFromUrl( questions/511761/js-function.min.js?bar=9.9&y=1#/src/jjj?=9.9 )).toBe( js-function.min.js )
  })
})

同样,“用户2492653”建议,如果你想要的是档案名称,如“德国”就给你,那么,“分裂”方法就把雕像分解成一系列部件,那么,你们都需要做完最后的索引。

var temp = url.split("//");
if(temp.length > 1)
 return temp[temp.length-1] //length-1 since array indexes start at 0

这基本上会打碎C:/fakepath/test.csv到{“C:”、“fakepath”、“test.csv”}

我的2%

如果碎片含有“/”的,则最后IndexOf(“/”)方法本身就会下降。

我们都知道,它们“应当”被编码为%2F,但只有一种非替罪价值才能引起问题。

这一版本正确地处理了问题,没有依赖。 页: 1

function getPageName() {
    //#### Grab the url
    var FullUrl = window.location.href;

    //#### Remove QueryStrings
    var UrlSegments = FullUrl.split("?")
    FullUrl = UrlSegments[0];

    //#### Extract the filename
    return FullUrl.substr(FullUrl.lastIndexOf("/") + 1);
}

引言

url.substring(url.lastIndexOf( / )+1, url.length)
url? url.substring(url.lastIndexOf( / )+1, url.lastIndexOf( . )):  
  • Safety is as asked for. when url is null or undefined the result is .
  • Removes all of the path with : , dots and any symbol including the last / .
  • This gives the true answer th as asked and not th.index . That is very important of course to have it work at all.
  • 它允许档案名称有几期。

  • 没有人问过,但你也可以有一个没有或没有发现的麻烦。

www.un.org/Depts/DGACM/index_spanish.htm 这是Abhishek Sharma的更正答复,因此,我给他一个 up。 气温和最小的单行——我在那里看到:

ES6 syntax based on TypeScript

实际上,有标记的答复是真实的,但如果是第二个<条码>>。 页: 1 我更喜欢写如下:

const getFileNameFromUrl = (url: string): string => {
  if (url) {
    const tmp = url.split( / );
    const tmpLength = tmp.length;

    return tmpLength ? tmp[tmpLength - 1] :   ;
  }

  return   ;
};

对于我的问题,我需要延长档案。

Simple Function (Using RegEx Pattern)

function pathInfo(s) {
    s=s.match(/(.*?/)?(([^/]*?)(.[^/.]+?)?)(?:[?#].*)?$/);
    return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}

var sample= /folder/another/file.min.js?query=1 ;
var result=pathInfo(sample);
console.log(result);
/*
{
  "path": "/folder/another/",
  "file": "file.min.js",
  "name": "file.min",
  "ext": ".js"
}
*/
console.log(result.name);

Using RegEx

让我说,你有这一ur:

http://127.0.0.1:3000/pages/blog/posts/1660345251.html

采用以下法典:

var filename = location.pathname.replace(/[D]/g, "");

返回:

1660345251
  • Notice that this number is Unix Time, which returns your local time no matter where you are in the World (this should give you really unique post names for this blog example).
  • .replace(/[D]/g, ""), replaces any non-digit character with an empty string. /[D]/g says non-digit, and "" says empty string. More about it: here for numbers and here for letters.
  • More about RegEx, here. There are lots of RegEx tools out there that can help you out to get better results in the returning value for filename.

Extra code: Unix Time to Local Time

var humanDate = new Date(0);
var timestamp = entries[index].timestamp;
humanDate.setUTCSeconds(timestamp);

当地时间:

Fri Aug 12 2022 20:00:51 GMT-0300 (Argentina Standard Time)

>here

function getFilenameFromUrlString(url) {
 const response = {
   data: {
     filename: ""
   },
   error: ""
 };
 try {
   response.data.filename = new URL(url).pathname.split("/").pop();
 } catch (e) {
   response.error = e.toString();
 }
 return response;
}

For tests check this: https://codesandbox.io/s/get-filename-from-url-string-wqthx1

https://stackoverflow.com/questions/423376/how-to-get-the-file-name- from-a-full-path-using-javascript> 如何利用Java语从一条完整的道路上获取档案名称?

var filename = fullPath.replace(/^.*[\/]/,   )




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签