简体   繁体   中英

Get Filename from URL and Strip File Extension

I need to get just the filename without the extension from a url and can't quite get there.

Here's my url in question: https://www.mealenders.com/shop/index.php/shop/solo-pack.html

Here's what I've tried:

function () {
 var value={{Page Path}}.split("/");
 return value.reverse()[0];
 }

That almost gets me there as it returns "solo-pack.html". What else do I need to do to get rid of the ".html" for this?

Thanks in advance.

You can do the following using javascript. Pop returns the last element which is a string, and then you can use the replace function to get just the filename without.html on the end.

function getFilename () {
  return {{ Page Path }}.split('/').pop().replace('.html', '');
}

I see that {{ Page Path }} is probably some templating language but you could modify the above script, to get the current URL and then get the filename as so.

function getFilename () {
  return window.location.href.split('/').pop().replace('.html', '');
}

Furthermore you could make it more dynamic to handle any file extension with the following. You need to get the index of the period using indexOf and then sub string from the start of the filename up to the position of the period.

function getFilename () {
  var filename = window.location.href.split('/').pop();
  return filename.substr(0, filename.lastIndexOf('.');
}

 function getFileName(url) { return url.split("/").pop().split(".")[0]; } var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html"; console.log(getFileName(url));

I need to get just the filename without the extension from a url and can't quite get there.

Here's my url in question: https://www.mealenders.com/shop/index.php/shop/solo-pack.html

Here's what I've tried:

function () {
 var value={{Page Path}}.split("/");
 return value.reverse()[0];
 }

That almost gets me there as it returns "solo-pack.html". What else do I need to do to get rid of the ".html" for this?

Thanks in advance.

If you need to get rid of any extension, you can use .replace() with regular expression:

 var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html"; function getFilename (path) { return path.toString().split('/').pop().replace(/\.\w+$/, ''); } console.log(getFilename(url));

This will for example change test/index.html into index but index.php.default into index.php and also test.name.with.dots.txt -> test.name.with.dots

function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
 }

Short and sweet:

"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")

Returns:

solo-pack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM