Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 hello-test@ 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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You may try using match() here:

var sample = " test-abc -test# @test _test hello-test@ test test ";
var matches = sample.match(/(?<=\s)test|test(?=\s)/g, sample);
console.log("There were " + matches.length + " matches of test with whitespace on one side");

The regex pattern used here says to match:

(?<=\s)test  test preceded by whitespace
|            OR
test(?=\s)   test followed by whitespace

Note that the 5 matches here were:

test-abc
@test
_test
test
test
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda