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

77
Visualizações
How can i count a specific words in a certain string?

i'm new to javascript langguage and still learning some of the data types and i get execise which i can not comprehend, please help me.

The exercise question :

'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence.

so i tried some of the basic method such as,

  1. match
  2. search
  3. split

and i cannot count the words love and given love words index.

how can i code this to find the answers?

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

0

This should work.

let sentence = "Love is the best thing in this world. 
Some found their love and some are still looking for their love."

console.log(sentence.split("love").length)
about 4 years ago · Juan Pablo Isaza Relatório

0

This should work

const sentence = 'Love is the best thing in this world. Some found their love and some are still looking for their love.'
const occurrences = sentence.match(/love/gi); // (g is is for match all occurrences, i is for case insensitive)
console.log("number of occurrences of 'love'", occurrences.length)
about 4 years ago · Juan Pablo Isaza Relatório

0

To make it a little more generic and to show of the use of reduce:

const data = "Love is the best thing in this world. Some found their love and some are still looking for their love"

const dataArray = data.split(' ');

const wordMap = dataArray.reduce((result, word) => {
    result[word.toLowerCase() ]= result[word.toLowerCase() ] ? result[word] + 1 : 1;
    return result
}, {});

console.log(wordMap["love"])
console.log(wordMap["is"])
console.log(wordMap["best"])

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