For example, assuming that x = filename.jpg
, I want to get filename
, where filename
could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).
I saw x.substring(0, x.indexOf('.jpg'))
on DZone Snippets, but wouldn't x.substring(0, x.length-4)
perform better? Because, length
is a property and doesn't do character checking whereas indexOf()
is a function and does character checking.
If you have to process a variable that contains the complete path (ex.:
thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg"
) and you want to return just "filename" you can use:the result will be theName == "filename";
To try it write the following command into the console window of your chrome debugger:
window.location.pathname.split("/").slice(-1).join().split(".").shift()
If you have to process just the file name and its extension (ex.:
theNameWithExt = "filename.jpg"
):the result will be theName == "filename", the same as above;
Notes:
But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.
working snippet 1: the complete path
working snippet 2: the file name with extension
working snippet 2: the file name with double extension
This is where regular expressions come in handy! Javascript's
.replace()
method will take a regular expression, and you can utilize that to accomplish what you want:Here's another regex-based solution:
This should only chop off the last segment.
You can perhaps use the assumption that the last dot will be the extension delimiter.
If file has no extension, it will return empty string. To fix that use this function
In Node.js versions prior to 0.12.x:
path.basename(filename, path.extname(filename))
Of course this also works in 0.12.x and later.
I like this one because it is a one liner which isn't too hard to read: