what i need to get single "parameter" from a "full url" in Javascript like the example below :
example :
http://cms.example.com ----> cms
What i have done till now and tried windows.location.href.split('.');
Javascript code
var y = window.location.href.split('.');
var z = y[0];
console.log(z); //output http://cms
here output is not coming what i needed can anyone help?
thanks in advance.
4 Answers 4
Use location.host
as it doesn't have the protocol. It's worth to mention that this method is not reliable. If you don't have www
or a subodmain, the root domain will be returned (like in the snippet below)
var y = window.location.host.split('.');
var z = y[0];
console.log(y);
console.log(z); //output http://cms
Comments
Comments
Using split
you could try this one:
s.split("//")[1].split(".")[0]
where s
is your string. In the first split
, we split the string on //
and we take an array of two items, the second item is the domain name. Then splitting the domain name on .
you get an array of it's parts and the first item is that you are looking for.
var s = "http://cms.example.com";
var r = s.split("//")[1].split(".")[0];
console.log(r);
Comments
Try it
window.location.href.split('.')[0].split('//')[1];
substring
to your result? Maybe something likeif( z[ 4 ] == 's' ) z = z.substring(0, 7); else z = z.substring(0, 6);
( the test is in case you have https instead of http )