Extract the domain from a URL

This script is part of the Keywords in Sheets Free Add-On.

With this script you can input a range of URLs and the formula will extract the domain from the URLs (with or without the protocol). 🚀

Check out the GIF to see it in action 🎥

How to add the Script to Google Sheets

1. Copy the script below:

 * Extract the domain from a URL
 * @param {A2:A100} url - A range of URLs or a single URL
 * @param {false} protocol - If true, return the protocol eg. https://  
 * @customfunction

function domainextract(url, protocol) {

    // protocol false by default
    protocol = protocol || false;

    // if url is a single cell, return domain
    if (!Array.isArray(url)) {

        // if there is no domain or domain is not a valid URL, return error  
        if (!url || !url.match(/^https?:\/\//)) {
            return 'You need to enter a valid URL.';
        } else {
            if (protocol === true) {
                // return domain with protocol
                return url.match(/^https?:\/\/[^/]+/)[0];
            } else {
                // return domain without protocol
                return url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/i)[2];

    } else {

        // strip empty cells
        url = url.flat(Infinity).filter((value, index, array) => {

            // if the value is not empty, return true
            if (value) return true;

            // if the value is empty and the index is 0, return false  
            if (index === 0) return false;

            // if the value is empty and the index is the last value in the array, return false
            if (index === array.length - 1) return false;
            return true;

        let domains = [];

        // loop through each URL and, if valid, return domain
        for (let i = 0; i < url.length; i++) {
            if (!url[i].match(/^https?:\/\//) || !url[i]) {
            } else {
                if (protocol === true) {
                    // push domain with protocol
                } else {
                    // push domain without protocol
        return domains;

2. Head over to Google Sheets

Or if you’re really smart, create a new sheet by going to: https://sheets.new

Select Appscript from the Extensions menu.

Paste the script and save it.

3. Add the formula to any cell in your sheet

=domainextract(A2:A100, false)

Replace A2:A100 with any range of URLs (you can also run the formula on a single cell).

Change false to true if you want to include the protocol in the domains returns. eg. from example.com to https://www.example.com.

Thanks for stopping by 👋

I’m Andrew Charlton, the Google Sheets nerd behind Keywords in Sheets. 🤓

Questions? Get in touch with me on social or comment below 👇

More Scripts

Submit your response

Your email address will not be published. Required fields are marked *