简体   繁体   中英

Get specific part from url origin with JS

I have to extract a specific part from an url origin. But I can't seem to figure out a good and fail proof way to do this

For example, this is my url: http://site.domain.com

I need to know what "domain" is used. How do I get this part from the url 100% of the time?

My first thought was to split it between the "." but then I thought about what could happen if someone uses a http://www.site.domain.com link. That would mean it wouldn't work.

Further explanation:

I currently have 2 website which both have a differend domain name. I have to get the information about which page is loaded, based on the "domain" name in the url.

Thanks in regard!

Split by / using split("/") :

 function getDomain(url){ var arr = url.split("."); return arr[arr.length - 2]; } console.log(getDomain('http://site.domain.com')); console.log(getDomain('http://www.site.domain.com')); 

You could split it by "." and get the next to last text of your string.

 var str = 'http://www.site.domain.com'; var domain = str.split('.'); console.log(domain[domain.length-2]); 

Later Edit

To provide further fail proof, you can get the latest text between .com and the first dot before it. This will work in case you have another dot in your URL, for example: 'http://www.site.domain.com/post/test.asp' .

 var str = 'http://www.site.domain.com/post/test.asp'; var preComLink = str.substr(0, str.indexOf('.com')); var preDomainIndex = preComLink.lastIndexOf('.'); var domain = preComLink.substr(preDomainIndex + 1, str.indexOf('com')); console.log(domain); 

split the full domain name on dot and than take element before last element.

 var url = 'http://www.site.domain.com'; var array = url.split("."); var lengthOfArray = array.length; var domain = array[lengthOfArray-2]; console.log(domain); 

 let code = (function(){ return{ getDomain: function(url){ var slpitDomainURL = url.split("."); var lengthOfArray = slpitDomainURL.length; var domain = slpitDomainURL[lengthOfArray-2]; return domain; } } })(); console.log(code.getDomain('http://www.google.com')); console.log(code.getDomain('http://www.facebook.com')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM