I am very new to JavaScript, and I'm trying to figure out how to count how many times a single letter appears in a word. For example, how many times does 'p'
appear in 'apple'
Here is what I have written so far but am having trouble figuring out where am I going wrong.
var letterInWord = function (letter, word) {
var letter = 0;
var word = 0;
for (var i = 0; i < letter.charAt; i+= 1) {
if (letter.charAt(i) === " " = true) {
letter++;
console.log('The letter `letter` occurs in `word` 1 time.');
}
}
return letter;
};
You've got a number of problems:
letter.charAt
is undefined, if letter
is a number, and is a function if letter
is a string. Either way, i < letter.charAt
makes no sense. letter
in word
why do you want to look at letter.charAt(i)
? You probably want word.charAt(i)
. " " = true
makes no sense at all. Perhaps you meant something like this?
var letterInWord = function (letter, word) {
var count = 0;
for (var i = 0; i < word.length; i++) {
if (word.charAt(i) === letter) {
count++;
}
}
return count;
};
'apple'.match(/p/g).length // outputs 2
in other words:
var letterInWord = function (letter, word) {
return (word.match( new RegExp(letter, 'g') ) || []).length;
};
Here's a smaller function that also works with characters like $
or *
(and since it's calling length
on a string, there's no need to use || []
)
'apple'.replace(/[^p]/g,'').length // outputs 2
function charcount(c, str) {
return str.replace(new RegExp('[^'+c+']','g'),'').length
}
console.log = function(x) { document.write(x + "<br />"); };
console.log( "'*' in '4*5*6' = " + charcount('*', '4*5*6') ) // outputs 2
console.log( "'p' in 'pineapples' = " + charcount('p', 'pineapples') )// outputs 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.