We would like to know how to count how many times a single letter appears in a word.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!-- w ww .j av a 2 s.co m-->
var letterInWord = function (letter, word) {
return (word.match( new RegExp(letter, 'g') ) || []).length;
};
document.writeln( letterInWord('p', 'apple') )
document.writeln('<br/>');
document.writeln( letterInWord('k', 'conduct k') )
document.writeln('<br/>');
document.writeln( letterInWord('d', 'test') )
}
</script>
</head>
<body>
</body>
</html>
The code above is rendered as follows: