José Ferreira
José Ferreira

Reputation: 45

Get specific part of a URL with JavaScript

I'm new to JavaScript, I need help solving a problem.

I have the following URL:

http://localhost/solo04/index.php?route=checkout/checkout#shipping-method

I would like to just get that part of the url (route =checkout/checkout) how to do this?

Upvotes: 1

Views: 3261

Answers (4)

shriek
shriek

Reputation: 5843

I'd like to throw this out too cause I don't think it's been mentioned here. You can use the new URL API too to avoid any regex or any string manipulation that I'm seeing on some of the answers here.

But this is relatively new so support for this in older browsers might be limited.

e.g:

var myURL = new URL('http://localhost/solo04/index.php?q=somequery');
console.log(myURL);

That will give you an object which should have path, hostname, search etc.

Upvotes: 3

Bas van Dijk
Bas van Dijk

Reputation: 10713

The easiest way is to use a regex or split:

url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method";

lastPart = url.split('?')[1]; // grabs the part on the right of the ?

console.log(lastPart);

More variants are listed How to get the value from the GET parameters?

Upvotes: 3

Alexander Craggs
Alexander Craggs

Reputation: 8819

You can create a hyperlink element to accomplish this, simply create it like you normally would but don't append it to the DOM:

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

If you then require the query-string, you can parse it using something like:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

In order to get a specific variable.

Credit to jlong & Tarik for the excellent ideas.

Upvotes: 2

Raj
Raj

Reputation: 2028

    var str1 = "http: //localhost/solo04/index.php? Route = checkout / checkout # shipping-method";
    var n = str1.lastIndexOf("?")+1;
    alert(str1.substr(n));

Upvotes: 0

Related Questions