Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.*/
like image 218
streetlight Avatar asked Jan 16 '13 13:01

streetlight


2 Answers

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;
}
like image 136
Shadow Wizard Hates Omicron Avatar answered Sep 23 '22 16:09

Shadow Wizard Hates Omicron


You can do it easier with string.split()...

function getPath() {
    var url = window.location;
    var path = url.split("/")[4];
    alert(path);
    return path;
}

I only suggest this method since you say you will always know the format of the URL.

like image 34
Reinstate Monica Cellio Avatar answered Sep 24 '22 16:09

Reinstate Monica Cellio