Javascript: Parse Domain Name out of a String

Did I mention that the “Web” category might contain code? It might. In fact, it will.

Here’s a random function I wrote last night that might be useful


function getDomain (thestring) {
//simple function that matches the beginning of a URL
//in a string and then returns the domain.
var urlpattern = new RegExp("(http|ftp|https)://(.*?)/.*$");
var parsedurl = thestring.match(urlpattern);
return parsedurl[2];
}

Is there a better way to do that? I don’t know. The momentum of “I’ve got to get this done”, got in the way and left me with the above function.

One thought on “Javascript: Parse Domain Name out of a String

  1. Hi,

    Thanks for sharing this. I needed to extract the domain and looking over your solution helped me save plenty of time trying to write the RegEx.

    Thanks,
    -Patel

Leave a Reply

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