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?
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?
Share Improve this question edited Jun 10, 2017 at 2:27 shriek 5,8538 gold badges52 silver badges83 bronze badges asked Jun 8, 2017 at 14:07 José FerreiraJosé Ferreira 452 silver badges9 bronze badges 1- stackoverflow./questions/39619951/… – Millard Commented Jun 8, 2017 at 14:09
4 Answers
Reset to default 3The 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?
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.
You can create a hyperlink element to acplish 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.:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example."
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.: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.
var str1 = "http: //localhost/solo04/index.php? Route = checkout / checkout # shipping-method";
var n = str1.lastIndexOf("?")+1;
alert(str1.substr(n));