Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

difficulty in finding letters and words in a string

I have text and want to find the number of letters like ‘a’, ‘i’, and also the word ‘it’. I’ve been able to find the number of letters ‘a’ and ‘i’, but for the word ‘that’ I can’t find

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]

result_a = [];
result_i = [];
result_it = [];

for (let i = 0; i < words.length; i++) {
    for (let j = 0; j < text.length; j++) {
        if (words[i] == text[j] && words[i] == words[0]) {
            result_a.push(text[j]);
        } else if (words[i] == text[j] && words[i] == words[1]) {
            result_i.push(text[j])
        } else if (words[i] == text[j] && words[i] == words[2]) {
            result_it.push(text[j])
        }
    }
}

console.log(result_a.length) //13
console.log(result_i.length) //24
console.log(result_it.length) //0

The output I expect is the number of each word searched for, for example the number of ‘a’ in the text variable is 13

my code is too long, is there a more concise way? and how to find ‘it’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let text = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, perspiciatis? Reiciendis, facere nobis libero officiis labore sit, deserunt maiores perferendis tempore quas neque odit. Quasi culpa totam aspernatur deserunt nobis."
let words = ["a", "i", "it"]
var wordToCount = {};

words.forEach( word => {
  let searchText = new RegExp(word, 'g')
  var matchCount = (text.match(searchText) || []).length;
  wordToCount[word] = matchCount;
});

for (const [key, value] of Object.entries(wordToCount)) {
  console.log(key, value);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading