Here's a quick Javascript function that will parse the filename from a path using regex. It looks for any letter or digit, hyphen, or underscore followed by a dot (.) followed by a letters or numbers for the extension.
function getFileName(path) { return path.match(/[-_\w]+[.][\w]+$/i)[0]; }
Hi, what i don't want the extension, how should i return the path. Thanks.
ReplyDeletenot working for filenames having empty spaces.
ReplyDeleteJust tweak the regex a bit. This will look for any character that isn't a forward slash or dot so you can have special chars in the filename as well:
ReplyDelete[^/]+[.][\w]+$
i want to get file name from directory and then display on web page using javascript
ReplyDeleteThanks man! You save my time!!! Thank you!!!
ReplyDeleteThe regex you are using is not Accurate , dosn't get all kind of names
ReplyDeleteThanks your function helped alot....
ReplyDeleteThis won't match if you have other characters that arent hyphens or underscores (like percent signs for url encoded characters). What i ended up doing was just slicing at / and popping the last one off the end.
ReplyDeletefunction getFileName(path) {
return path.split('/').pop();
}