Reputation: 43
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.
Upvotes: 4
Views: 6959
Reputation: 7925
Short and sweet:
"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")
Returns:
solo-pack
Upvotes: 0
Reputation: 3113
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
Upvotes: 0
Reputation: 2638
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('.');
}
Upvotes: 6
Reputation: 3030
function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
}
Upvotes: 0
Reputation: 4505
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));
Upvotes: 0