user1223680 user1223680 - 1 year ago 77
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


For example the contents of my variable (named
) would look like
. 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 Source

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(/^.*\/(?=[^\/]*$)/, '');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download