Here我发布了一个问题,但我仍然停留
是我的文本吗?
Toto1 The line Toto2 The line Toto3 The line Toto2 The line (second) Toto3 The line (second) ...
当我搜索“ Toto2”时,有必要恢复包含“ Toto2”的每一行,也有必要计算包含“ Toto2”的行数,这可能吗?
var regex = new RegExp('Toto2.*\n', 'g');
有了这个,我们必须返回这个:
Toto2 The line Toto2 The line (second)
和其他变量:
2
谢谢
答案 0 :(得分:1)
您可以通过简单的正则表达式使用Array.prototype.filter
:
const text =
`Toto1 The line
Toto2 The line
Toto3 The line
Toto2 The line (second)
Toto3 The line (second)`;
const filteredLines = text.split('\n').filter(line => /Toto2/gi.test(line));
const count = filteredLines.length;
console.log(filteredLines);
console.log(count);
获取具有相应行号的行(借助Array.prototype.reduce
)
const text =
`Toto1 The line
Toto2 The line
Toto3 The line
Toto2 The line (second)
Toto3 The line (second)`;
const linesWithIndexes = text.split('\n').reduce((all, line, i) => {
return all.concat(/Toto2/gi.test(line) ? {line, lineNumber: i + 1} : []);
}, []);
console.log(linesWithIndexes);