Sift through Text with Regular Expressions with a Function?

How would i make this code from this lesson https://www.freecodecamp.org/challenges/sift-through-text-with-regular-expressions work when using it in function? I tried it but it returns Invalid Javascript.

function myFunction(word) {

var string = "Michael is 22 and he is a web designer and he is also developer";

var find = /word/gi;
var count = string.match(find).length;

return count;

}
myFunction("is");

word is a variable, but in your find you are just creating a pattern for the actual letters 'word'.

Can you give me a example of how i would make code like this work in function? I knew i failed at something in this code lol.

Check out the regex documentation. If you use the constructor (new RegExp), then you could build the regular expression using word as a variable. You will also need to use the 2nd parameter which represents a flag. To count all matches instead of just the first match, you will need to use the “global match” flag. Also, if you want “is”, “Is”, “IS” to all be counted, then you would also need to use the “ignore case” flag.

2 Likes