0

There are lots of posts online like this, but none of them seem to do what I'm trying to do.

Let's say I have a domain in a string:

Extract hostname name from string

And I want to extract the domain name and nothing else (not the protocol, the subdomain or the file extension).

so for

https://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string

I want to get:

stackoverflow.com

Is there any way to do this?

Community
  • 1
  • 1
Jack Pilowsky
  • 2,275
  • 5
  • 28
  • 38
  • 1
    first log message in this answer: http://stackoverflow.com/a/736970 –  Jul 23 '14 at 00:44
  • As the post you are linking to suggests, it is usually a good idea to rely on a solid URL parsing function and then just keep the part you need. In terms of performance the difference will be negligible, and you'll gain in reusability and readability. – Christophe Jul 23 '14 at 00:45

2 Answers2

2

Try this on:

var url = 'http://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string';
var domain = url.match(/^https?:\/\/([^\/?#]+)/)[1];
alert(domain);

This looks for a string that starts with http and optionally s, followed by ://, then matches everything it can that is not a /. But .match() returns an array here:

['http://stackoverflow.com', 'stackoverflow.com']

So, we use [1] to get the submatch.

elixenide
  • 44,308
  • 16
  • 74
  • 100
0

You can use a simple regex like this:

\/\/(.*?)\/

Here you have a working example:

http://regex101.com/r/iP0uX7/1

Hope to help

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123