I have a url like http://www.example.com/blah/th.html
I need a javascript function to give me the \'th\' value from that.
All my urls have the same format (2
my 2 cents
the LastIndexOf("/") method in itself falls down if the querystrings contain "/"
We all know they "should" be encoded as %2F
but it would only take one un-escaped value to cause problems.
This version correctly handles /'s in the querystrings and has no reliance on .'s in the url
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);
}
Try this
url.substring(url.lastIndexOf('/')+1, url.length)
url? url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.')):''
null
or undefined
the result is ''
.It allows filename to have several periods!
Not asked, but you can also have a query string without '/' and '.'
It is a corrected answer from Abhishek Sharma so I gave him an upvote. So genious and minimal one-liner - I saw it there :)
function getFileNameWithoutExtension(url) {
if (typeof url !== 'string') throw new Error('url must be a string');
// Remove the QueryString
return url.replace(/\?.*$/, '')
// Extract the filename
.split('/').pop()
// Remove the extension
.replace(/\.[^.]+$/, '');
}
This will return news
from this URL http://www.myblog.com/news.php?year=2019#06.
Why so difficult?
var filename = url.split('/').pop().split('#')[0].split('?')[0];
For node and browsers, based on @pauls answer but solving issues with hash and more defensive:
export function getFileNameFromUrl(url) {
const hashIndex = url.indexOf('#')
url = hashIndex !== -1 ? url.substring(0, hashIndex) : url
return (url.split('/').pop() || '').replace(/[\?].*$/g, '')
}
Few cases:
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')
})
})