Skip to content

Instantly share code, notes, and snippets.

@usrrname
Last active November 30, 2019 22:56
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save usrrname/70819ab3421e1c3e93ed8accea212b88 to your computer and use it in GitHub Desktop.
find how many times a word repeats in a sentence
// Example Whiteboard Problem: Find the number of times a name, "bob", repeats in a sentence.
// input : string
// output : number
// example string: 'Once upon a time Bob had a farm. Bob was happy. bobbity bon';
// Attempt 1
const sentence = 'Once upon a time Bob had a farm. Bob was happy. bobbity bon';
const findRepeatingWord = (str) => {
let keyword = 'bob';
let count = 0;
// loop through the string
str.split(' ');
for (let i = 0; i < str.length; i++){
// find the matching words
if (i == keyword) {
// increment count
count++;
}
}
return count;
}
// Attempt 2
const findRepeatingWord = (string) => {
string.toLowerCase();
string.split();
let count = 0;
for (let word in string)
if( word.includes('bob', 0)){
return count++;
}
return count;
}
// Attempt 3
const findRepeatingWord = (str) => {
str.match(keyword/gi).length;
}
findRepeatingWord(sentence)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment