Regex pattern to count a certain occurrences

I am trying to match a word which have either space before it or after it or both .

var sample = " test-abc -test# @test _test [email protected] test test "

Like in the above case the first ‘test’ will count as it has a space before it, the next will not count as it has no space, the third ‘test’ will count as it has a space after it ,similarly the fourth one too, the fifth one will not count as it has no spaces front or back and the last two will as they have spaces before and after.

function countOccurences(str,word){
       var regex = new RegExp("(b|(?<=_))"+word+"(b|(?<=_))","gi");
       console.log((str.match(regex)|| []).length);

The function I have written count the exact word but do not consider the space so the output I get is 7 but what I am trying to get is 5.

Source: JavaSript – Stack Overflow

November 26, 2021
Category : News
Tags: javascript | match | regex | string

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.