我有以下内容:
var1 = "www.asite.page.co.uk";
var2 = '.' + var1.match(/\w*\.\w*$/) [0];
我知道它正在尝试实现“.co.uk”,但我不知道 [0] 的作用。 是错误处理吗?
最佳答案
match
返回一个数组的字符串。
没有全局标志,数组组成如下:
- 仅使用第一个匹配项。
- 第一个键
[0]
包含完整的第一个匹配项。 - 其他键包含第一个匹配项中匹配的组。
例子:
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)
当指定全局标志时,数组由所有完全匹配组成:
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)
我建议看看:
- MDN:RegExp
关于匹配语句末尾的 Javascript [0],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428518/