0

I want to split the website name and get only URL without the query string example: www.xyz.com/.php?id=1

the URL can be of any length so I want to split to get the URL to only xyz.com

able to split the URL and getting xyz.com/php?id=1 but how do I end the split and get only xyz.com

var domain2 = document.getElementById("domain_id").value.split("w.")[1];

  • 1
    Possible duplicate of [Is there any method to get the URL without query string?](https://stackoverflow.com/questions/5817505/is-there-any-method-to-get-the-url-without-query-string) – Charmander Oct 01 '19 at 15:18
  • @Charmander already gone through this, didn't found any solution there. – Tamanbir Singh Oct 01 '19 at 15:20
  • The query string is _part_ of the URL; see https://en.wikipedia.org/wiki/URL. The bit you want (www.xyz.com) is the "host". – Roger Lipscombe Oct 01 '19 at 15:20

3 Answers3

4

You can use:

new URL()

for example -

var urlData = new URL("http://www.example.org/.php?id=1")

and than

urlData.host

which will only return the hostname

user3628517
  • 93
  • 2
  • 10
0

You can use a simple regex with match to capture the host in the way you want:

var url = 'www.xyz.com/.php?id=1';
var host = url.match(/www.(.*)\//)[1];

console.log(host)
Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46
0

Just adding it to other, you can also use this regex expression to capture everything up until the query string "?" like so;

This will also work if you want to grab any sub pages from url before the query string

var exp = new RegExp('^.*(?=([\?]))');
var url = exp.exec("www.xyz.com/.php?id=1");
var host = url[0];

console.log(host);