It works if you write your code like this:
var arr = ["developer.mozilla.org", "cdn.mdn.mozilla.net", "www.google-analytics.com", "www.youtube.com"];
var arrLength = arr.length;
var reg = /[^.]+\.[^.]+$/
for (i=0; i< arrLength; i++)
{
console.log(arr[i].match(reg)[0])
}
Some explanations:
First of all there is a flaw in your regex that causes the 'google-analytics' entry to be missed. I would likely suggest that you write your regex like this instead
var reg = /[^.]+\.[^.]+$/
The regex you wrote has 2 capturing groups, this explains the arrays you are getting from your console.log
['.mozilla.org', '.mozilla', '.org'] = [matching string, capturedGroup1, capturedGroup2]
you could make your groups non-capturing by writing your regex like so:
var reg = new RegExp('(?:(?:\\.[a-zA-Z0-9]+)(?:\\.[a-zA-Z0-9]+))$');
or using a regex literal as @Bergi suggests
var reg = /(?:(?:\.[a-zA-Z0-9]+)(?:\.[a-zA-Z0-9]+))$/
in any case when you're using the match
method you'll get an array in return and what you're really interested in is the matched string, so the first element in the array. You'd get the expected result by rewriting the body of the loop like this
console.log((arr[i].match(reg) || [])[0]) // note I'm concerned with string.match returning null here
If you really dislike the array you could use string replace instead
console.log(arr[i].replace(/^.*\.([^.]+\.[^.]+)$/, '$1'))