0

If the value of window.location.hostname gives something like "example.com", How can I get just "example" out of the result?

How can I make window.location.hostname return without .com or .org

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
akash
  • 5
  • 1
  • 2

2 Answers2

1

Assuming it's a top level domain(and not, mail.somedomain.com), the following code would give you "somedomain" instead of "somedomain.com".

var basehost = window.location.hostname.split(".")[0];

Andrew Coder
  • 1,058
  • 7
  • 13
  • well, +1, But It only works if the user submits `www. + what you need + .rest of url` – Shafizadeh Oct 13 '15 at 22:55
  • Right. In that case it'd be index [1] instead of [0]... there is probably a better way to do this. Mine was very limited in use cases. – Andrew Coder Oct 13 '15 at 22:56
  • The OP seems to be after the domain name. I don't think there is any regular pattern you can use to determine that, given the variety of possible patterns. The hostname needs to be parsed with some intelligence. – RobG Oct 13 '15 at 23:44
  • I tried using window.location.hostname.slice(0, window.location.hostname.indexOf(".com")) but it does not work for localhost.Your solution works for localhost as well! Thank you! – akash Oct 14 '15 at 15:44
0

You can't make window.location.hostname 'return' anything different as you're using the inbuilt API that your browser provides.

What you can do instead is use some creative use of String.prototype.splitor a regex to manipulate the string value you get from that property.

Remember to consider cases like .co.uk where there is a dot in the middle of the TLD.

Ed_
  • 18,798
  • 8
  • 45
  • 71