Extracting everything after penultimate backslash

R

rl

Hi all,

What expression/function can I use to use extract a file's name and its directory,
i.e. how to get:-

'subdir1/file1.html' from /dir/subdir1/file1.html
or
'f/page.htm' from /dir1/dir2/dir3/f/page.htm

Regards, rl
 
M

Martin Honnen

rl said:
Hi all,

What expression/function can I use to use extract a file's name and its directory,
i.e. how to get:-

'subdir1/file1.html' from /dir/subdir1/file1.html
or
'f/page.htm' from /dir1/dir2/dir3/f/page.htm

var strings = [
"/dir/subdir1/file1.html",
"/dir1/dir2/dir3/f/page.htm"
];
var pattern = /[^\/]*\/[^\/]+$/;
for (var i = 0; i < strings.length; i++) {
var match = pattern.exec(strings);
if (match) {
alert(match[0]);
}
}
 
R

rl

Thanks Martin,

It works like a charm, here's what I've done with it:-

===============================================================
var strings = [
self.location.pathname
];

var pattern = /[^\/]*\/[^\/]+$/;
for (var i = 0; i < strings.length; i++) {
var match = pattern.exec(strings);
if (match) break;
}

var newURL = self.location.protocol +
'//' + self.location.host +
self.location.pathname.substring(0,self.location.pathname.lastIndexOf('/')) +
'/../index.html?contents.html&' + match[0];
===============================================================

Regards, rl
 
L

Lasse Reichstein Nielsen

rl said:
What expression/function can I use to use extract a file's name and its directory,
i.e. how to get:-

'subdir1/file1.html' from /dir/subdir1/file1.html
or
'f/page.htm' from /dir1/dir2/dir3/f/page.htm

function getDirectoryAndFileName(path) {
var lastSlash = path.lastIndexOf("/");
var nextToLastSlash = path.lastIndexOf("/",lastSlash-1);
return path.substring(nextToLastSlash+1);
}

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,083
Messages
2,570,591
Members
47,212
Latest member
RobynWiley

Latest Threads

Top