var data = `//foo bar
//bar foo
Something else with the word foo
//foo test more foo
//not has with defaul word - not match
`;
function getAllInstancesOfAWord(word) {
const regex = new RegExp(`^\/\/(.*${word}.*)`, 'gm');
console.log(regex);
// Use regex match function
const array = data.match(regex);
// console.log(array);
for (let i=0;i<array.length; i++){
console.log(`Found instance word contain "${word}" begin with "//" = ${array[i].substring(2)}`);
}
}
getAllInstancesOfAWord('foo');
getAllInstancesOfAWord('not');
1条答案
按热度按时间zf9nrax11#
使用以下示例:
注意事项:
^\/\/(.*foo.*)
:获取包含单词“foo”的示例字符串,以“//"开始。string.substring(2)
:获取从索引2开始到结束的所有字符,表示排除“//"。告诉我,我是不是错了你的想法,多知识多力量,对不对!