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

3

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

I like that. Very. Much. However, this won't work if the page url needs to be taken from within a routed page. e.g. www.xyz.com/users.php?id=1
i am trying to get the input through the form, so how can i use documen.getElementById in with this answer?
Try: var domain = new URL(document.getElementById("domain_id").value).host;
.host will include www., the OP mentioned he only wants xyz.com. Also, his example URL doesn't contain the schema (the http:// part).
@Titus exactly i need only xyz.com
|
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)

Comments

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

Comments

Your Answer

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.