Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

76
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!