Magiranu
Magiranu

Reputation: 309

Split URL from position x to the end in Javascript

In Javascript I get a part of my URL via location.pathname.

Example: /cakephp/public/home/Bob/documents

I would like to split the result beginning from /home till the end so that my result looks like this: /home/Bob/documents. Important to note is that the end is not fixed. After /documents could come more.

With location.pathname.split('/')[4] I get Bob. But how can I get /home/Bob/documents/... via the split() method?

Upvotes: 0

Views: 88

Answers (3)

Jamie McElwain
Jamie McElwain

Reputation: 462

If you use '/home' as the split argument, you can append the second element in the resulting array to the string '/home':

'/home' + location.pathname.split('/home')[1]

Edit:

If there is more than one '/home' in the string, you'll need to handle that like this:

let splitPath = location.pathname.split('/home')

splitPath.splice(0,1)

and then you can get the processed path with:

'/home' + splitPath.join('/home')

Upvotes: 3

Gorka Hernandez
Gorka Hernandez

Reputation: 3958

This method takes care of cases in which the /home string appears more than once in the URL, such as:

/cakephp/public/home/Bob/documents/pictures/home/bathroom

But equally handles other paths.

function getUrl() {
    let splitUrl = location.pathname.split('/home'),
        result = '';

    for (let i = 1; i < splitUrl.length; i++) {
        result += '/home' + splitUrl[i];
    }

    return result;
}

Upvotes: 1

Rohit Kumar
Rohit Kumar

Reputation: 1792

location.pathname.split('/'public')[1]

Upvotes: 1

Related Questions