2

I'm trying to return the number of times a letter appears in a word.

I'm passing the letter to a function like so

function getCount(letter)
{
    var pattern = '/' + letter + '/g';
    var matches = word.match(pattern);
    return matches.length;
}

Unfortunately matches is null so I'm unable to call length on it, I know the letter appears in the word as I've already checked that

word.indexOf(letter) > -1

I suspect the problem is with the way I'm building or evaluating pattern

2 Answers 2

8

Here's how you build a non literal regular expression :

var pattern = new RegExp(letter, 'g');

See the MDN on building a regular expression.

And here's a simpler solution to count the occurrences of the letter :

return word.split(letter).length-1;
Sign up to request clarification or add additional context in comments.

6 Comments

If I could give +2 for the alternative solution, I would. Sadly +1 is all I can offer.
@Kolink Unfortunately I just realized my alternate solution wasn't so good. It's less elegant now...
Or word.split(letter).length-1.
@MikeM This was my first answer but the problem is that it doesn't work if the letter is at start or end of the word.
It does for me! 'ergo'.split('e').length - 1; // 1. It's a neat solution anyhow.
|
2

You can do this:

function hasClass(letter) {
    var pattern = new RegExp(letter,'g'); // Create a regular expression from the string
    var matches = word.match(pattern);
    return matches;

Ref: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp

This was also answered here: javascript new regexp from string

3 Comments

Do you realize that this is the answer I made 10 minutes before ?
I had typed it all and was just grabbing the reference when the message came up, so I just clicked submit anyway.
sorry for not catching the dupe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.