Ad

How Can I Use A Reg Ex To Grab The Super-domain?

- 1 answer

as opposed to the sub-domain.

I tried.

  var a = window.location.hostname.match(/(www.)?([^\.]*)\./)[2];

but this will grab

frozen-dusk-2587

from

https://frozen-dusk-2587.herokuapp.com/

and I just want

herokuapp

also I want it to work if there is multiple sub domains and just grab the last...for example

x.x.x.y.com

will always grab

y
Ad

Answer

var a = window.location.hostname.match(/(?:\.|^)([^\.]+)\.(?:[^\.]+)$/)[1];

This only matches the last two parts of the hostname, and only captures the second to last.

(?:\.|^)   -- (?: ... ) is a non-capture group (eg. not kept in your match)
           -- \.|^  matches a dot or the start of the string
([^\.]+)   -- capture  all characters that are not a dot
\.         -- matches a dot
(?:[^\.]+) -- non-capture - "all characters that are not dots"
$          -- match end of string

Without regular expressions you can do the following (as per @cade-galt 's comment suggested by @Pointy):

var a = window.location.hostname, b = a.split('.'), c = b[b.length-2];

Ad
source: stackoverflow.com
Ad