I have the following:
var1 = "www.asite.page.co.uk";
var2 = '.' + var1.match(/\w*\.\w*$/) [0];
I understand that it's trying to achieve ".co.uk", but I have no idea what the [0] does. Is it error handling?
I have the following:
var1 = "www.asite.page.co.uk";
var2 = '.' + var1.match(/\w*\.\w*$/) [0];
I understand that it's trying to achieve ".co.uk", but I have no idea what the [0] does. Is it error handling?
Share Improve this question edited Feb 24, 2012 at 10:07 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Feb 24, 2012 at 9:42 user1230424user1230424 214 bronze badges4 Answers
Reset to default 4match
returns an array of strings.
Without the global flag, the array is posed as follows:
- Only the first match is used.
- The first key,
[0]
, contains the full first match. - The other keys contains the matched groups within the first match.
Example:
var string = 'abc_123_abd_456';
var regexp = /_([0-9])/; // Matches an underscore, and groups a number
var match = string.match(regexp);
// match[0] = _1 (full match)
// match[1] = 1 (group)
When the global flag is specified, the array consists of all full matches:
var string = 'abc_123_abd_456';
var regexp = /_([0-9])/g; // Matches an underscore, and groups a number, GLOBAL
var match = string.match(regexp);
// match[0] = _1 (first full match)
// match[1] = _4 (second full match)
I remend to have a look at:
- MDN: RegExp
The match method returns an array of matches, so the [0] gets the first element of that array -- i.e. just the full match.
See the documentation for match or Rob W's answer for a more plete description.
See RobW's answer for plete and accurate reference.
The match method returns an array.
The match() method searches for a match between a regular expression and a string, and returns the matches.
This method returns an array of matches, or null if no match is found.
The [0]
is used to return only the first element.
When you need one single string, it's often practical to use replace
rather than match
:
var1 = "www.asite.page.co.uk";
var2 = '.' + var1.replace(/.+?(\w*\.\w*)$/, '$1'); // .co.uk
BTW, your expression doesn't look right to me. A better way to match TLD would be something like
(\.[a-z]+\.[a-z][a-z]|\.[a-z]{3,})$
which matches both '.co.uk' and '.'. Example:
tld = "site.co.uk".replace(/.+?(\.[a-z]+\.[a-z][a-z]|\.[a-z]{3,})$/, '$1'); // .co.uk
tld = "yyy.".replace(/.+?(\.[a-z]+\.[a-z][a-z]|\.[a-z]{3,})$/, '$1'); // .