user1223680 user1223680 - 4 days ago 5
Javascript Question

Removing data before the last forward slash in a string

I have a file location in a variable and all I need to do is get the value from the last

/
onwards.

For example the contents of my variable (named
myfile
) would look like
/home/tony/files/test.pdf
or
/tmp/admin.doc
. I just want to go to the end of the variable and go backwards until I get to a
/
and then take the value from that point onwards.

Any ideas?

Answer

You can accomplish this using String.substring() and String.lastIndexOf():

var index = myfile.lastIndexOf('/');
if(index != -1)
{
    var newStr = myfile.substring(index + 1);
}

Another method of doing this would be to use regular expressions:

var newStr = myfile.replace(/^.*\/(?=[^\/]*$)/, '');
Comments