Home > other >  Regex pattern to match the whole line which has the match string
Regex pattern to match the whole line which has the match string

Time:11-25

I have a pattern which match the exact substring in a string

function search(str,word){
    var regex = new RegExp("(\\b|(?<=_))" word "(\\b|(?=_))","gi");   
    return str.match(regex);
}
var sample =`Hello this is 
a _test.
This is third-test
This is fourth line`
var result = search(sample,"test");
console.log(result);

The result is [ 'test', 'test' ] But I want the whole line where the match is happening i.e the output should be [ 'a _test', 'This is third-test' ]

CodePudding user response:

You may match on the regex pattern (?<=\n).*test.*(?=\n|$):

var sample = `Hello this is 
a _test.
This is third-test
This is fourth line`;

lines = sample.match(/(?<=\n).*test.*(?=\n|$)/g);
console.log(lines);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Another approach, splitting the input into separate lines, and then checking each line:

var sample = `Hello this is 
a _test.
This is third-test
This is fourth line`;

var lines = sample.split(/\n/);
var output = [];
for (var i=0; i < lines.length;   i) {
    if (lines[i].includes("test")) {
        output.push(lines[i]);
    }
}

console.log(output);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related