Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a Javascript Regex from string

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

like image 945
Luke Avatar asked Apr 14 '26 14:04

Luke


1 Answers

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;
like image 82
Denys Séguret Avatar answered Apr 16 '26 02:04

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!