'How can I turn this into a function that takes 2 arguments - a sentence and then the word I want to count in the string?
I am a newbie here. I had a technical assessment the other day and had a coding question where I had to write a function that took two arguments, a sentence and a word. The function had to count how many times the word was repeated in the sentence. I have managed to get the answer doing it the first way you see below but cannot for the life of me seem to figure it out as a function that takes 2 arguments which is what the task asked for. Can anyone tell me where I am going wrong please?
let count = 0;
let str = "hello hello hello Bob is my name so it is hello"
let query = "hello";
let array = str.split(" ")
for (let i = 0; i < array.length; i++) {
if (array[i] === query) {
count++;
}
}
console.log(count);
let str = "hello my name is my my bob";
let word = "my";
function countWord(str, word) {
let count = 0;
let strArray = str.split(" ");
let array = strArray;
for (let i = 0; i < array.length; i++) {
if (array[i] === word) {
count++
}
}
}
console.log(countWord(str, word));
Solution 1:[1]
Your only problem is that you're missing return count at the end of your function.
const sentence = 'hello there this is another hello hello test hello';
const word = 'hello';
function testString (sen, word) {
const split = sen.split(' ');
let count = 0;
for (let i = 0; i < split.length; i++) {
if (split[i] === word) {
count++;
}
}
return count;
}
console.log(testString(sentence, word));
Solution 2:[2]
You can also achieve this requirement with a single line of code using regex.
Demo :
let str = "hello my name is my my bob";
let word = "my";
console.log(str.match(new RegExp('\\b'+word+'\\b','g')).length);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rohìt JÃndal |
