Reputation: 65
I'm trying to get domain extension from a URL with jQuery. But not sure how to cover all possible scenarios. Highlighted the parts I need to get from the URL;
https://www.amazon.**com**/dp/067144901X
https://www.amazon.**co.uk**/dp/067144901X
https://www.amazon.**it**/dp/067144901X
https://www.amazon.**de**/dp/067144901X
$(".get").on('click', function(event) {
var DomainEX = $('#url').val();
alert(DomainEX);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="url">
<button class="get">GET</button>
Upvotes: 1
Views: 675
Reputation: 206228
Usually to extract parts from an URL the URL API might come handy. In your case the url.hostname
but this returns all the parts of a domain (including subdomain and extension).
For your specific case you could use a bit of regex:
const getAmazonExt = url => /amazon.([^/]+)/.exec(url)[1];
console.log(getAmazonExt('https://www.amazon.com/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.co.uk/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.it/dp/067144901X'))
console.log(getAmazonExt('https://www.amazon.de/dp/067144901X'))
Upvotes: 1
Reputation: 1751
You can convert to URL, get the host name:
const hostName = (new URL('https://www.amazon.com/dp/067144901X')).hostname;
Then extract everything that is after the site name:
const extension = hostName.split('amazon').pop()
//https://www.amazon.com/dp/067144901X
//https://www.amazon.co.uk/dp/067144901X
function getDomainExtension(url, siteName) {
const hostName = (new URL(url)).hostname;
const extension = hostName.split(siteName).pop()
console.log(hostName)
return extension;
}
$(".get").on('click', function(event) {
var DomainEX = $('#url').val();
const extension = getDomainExtension(DomainEX, 'amazon')
console.log(extension)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="url">
<button class="get">GET</button>
Upvotes: 2