1

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.

asked Aug 22, 2016 at 11:16
4
  • read on this w3schools.com/jsref/obj_location.asp Commented Aug 22, 2016 at 11:16
  • it wont work... i have tried this is something different Commented Aug 22, 2016 at 11:17
  • If your own solution almost suits you, why not doing substring to your result? Maybe something like if( 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 ) Commented Aug 22, 2016 at 11:19
  • window.location.href.split('.')[0].split('//')[1] this will give final result .. Are you try it.. @adasdasd Commented Aug 22, 2016 at 11:20

4 Answers 4

1

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

answered Aug 22, 2016 at 11:18

Comments

0

Try this:

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

See MDN

answered Aug 22, 2016 at 11:18

Comments

0

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

answered Aug 22, 2016 at 11:19

Comments

0

Try it

window.location.href.split('.')[0].split('//')[1];
answered Aug 22, 2016 at 11:22

4 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
Its Working fine @ppeterka
I didn't question that. Please read the help on how to post answers. Without any explanation, this only qualifies as a comment.
Ok thanks... @ppeterka .. But i will give explanation if questioner don't know about jquery function like split ,window.location.href etc..

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.