Aman
Aman

Reputation: 838

get the single parameter in URL in javascript

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.

Upvotes: 1

Views: 85

Answers (4)

Kumar Rakesh
Kumar Rakesh

Reputation: 2708

Try it

window.location.href.split('.')[0].split('//')[1];

Upvotes: 0

Christos
Christos

Reputation: 53958

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);

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

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

Upvotes: 1

haim770
haim770

Reputation: 49095

Try this:

location.host.split('.')[0]

See MDN

Upvotes: 0

Related Questions