getting a substring in javascript

W

windandwaves

windandwaves said:
Hi Folk

I have the following string:

http://www.myurl.com/folderbit/moerfiasdfsadf/sdaf/01354.jpg

and I want to extract the filename from it.

Do you know how to do this, if I don't know the exact names of the
folders, etc...

Thank you.

This is what I came up with. I use a generic replace function just because
I am a little lazy (who is not?)

function getimagename(f) {
f = f.substring(f.lastIndexOf('/'))
f = replace(f, ".jpg", "");
return f;
}

function replace(s, t, u) {
/* ** s string to be processed ** t token to be found and removed
** u token to be inserted */
i = s.indexOf(t);
r = "";
if (i == -1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length) {
r += replace(s.substring(i + t.length, s.length), t, u);
}
return r;
}
 
S

Stephen Chalmers

windandwaves said:
This is what I came up with. I use a generic replace function just because
I am a little lazy (who is not?)

function getimagename(f) {
f = f.substring(f.lastIndexOf('/'))
f = replace(f, ".jpg", "");
return f;
}

function replace(s, t, u) {
/* ** s string to be processed ** t token to be found and removed
** u token to be inserted */
i = s.indexOf(t);
r = "";
if (i == -1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length) {
r += replace(s.substring(i + t.length, s.length), t, u);
}
return r;
}


function nameFromPath( path )
{
var re=/\/([^\.\/]+\.[^\.\/]+)$/.exec( path );

return re ? re[1].replace(/\.[^\.]+/,'') : "" ;
}

alert(
nameFromPath('http://www.myurl.com/folderbit/moerfiasdfsadf/sdaf/01354.jpg'))
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Sat,
18 Feb 2006 10:02:35 remote, seen in
windandwaves said:
I have the following string:

http://www.myurl.com/folderbit/moerfiasdfsadf/sdaf/01354.jpg

and I want to extract the filename from it.

Some consider the filename to include the extension; some do not.

S = "http://www.myurl.com/folderbit/moerfiasdfsadf/sdaf/01354.jpg"

S = S.replace(/.+\/(.+)/, "$1") // 01354.jpg

S = S.replace(/.+\/(.+)\..+/, "$1") // 01354

The second presumes that there *is* a non-empty extension; this does
not, but returns only the filename proper :-

S = S.replace(/.+\/([^.]+).*/, "$1")

Consider also

S = S.match(/.+\/([^.]+).*/)[1]
 

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

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top