Issues with indexOf and lastIndexOf on substring - Get Part of URL from string

streetlight picture streetlight · Jan 16, 2013 · Viewed 14.4k times · Source

I'm having a few issues breaking apart a string in the way I want. I have a url like this:

http://SomeAddress.whatever:portWhatever/someDirectory/TARGETME/page.html

I'm trying to get the TARGETME portion on the string, using substring and indexOf instead of regex. This is the function I'm working with now:

 function lastPartofURL() {
    // Finding Url of Last Page, to hide Error Login Information
    var url = window.location;
    var filename = url.substring(url.lastIndexOf('/')+1);
    alert(filename);
}

However, when I wrote this I was targeting the 'page.html' part, so that's what it returns, but I'm having trouble reconfiguring this to do what I want it to do now.

If possible, I would like it to originate from the beginning of the string rather than the end, as there should always be a url and then one directory before what I'm trying to target, but I'm interested in both solutions.

Here is a regex that does something similar, but it's not secure (according to JSLint), and therefore I wouldn't mind replacing it with something more functional.

 /^.*\/.*\/TARGETME\/page.html.*/

Answer

As already answered by others, .split() is good for your case however assuming you mean to return "the part before last" of the URL (e.g. return "TARGETME" for http://SomeAddress.whatever:portWhatever/dirA/DirB/TARGETME/page.html as well) then you can't use fixed number but rather take the item before last of the array:

function BeforeLastPartofURL() {
    var url = window.location.href;
    var parts = url.split("/");
    var beforeLast = parts[parts.length - 2]; //keep in mind that since array starts with 0, last part is [length - 1]
    alert(beforeLast);
    return beforeLast;
}