Help with String.match()

Hello all,

I can’t understand how match() works.
I want to check if a substring is contained in a string, independently if the word has capital first letter or not. So I have this code:

var string = “Find my word”;
var w = “word”;
var substring = w;
var pattern = “/” + w + “/i”;

If I try:

string.match(substring); //This is working.
string.match(pattern); //This is not working and I got null.

Any idea why it’s not working as I expect?
Thank you!!

You can’t assemble regex that way. You’ll have to use a regex constructor call.

var w = 'word';
var pattern = new RegExp(w, 'i');

RegExp on MDN

Hi!

The reason why string.match(pattern) isn’t working is because your pattern variable is a string and not an actual regular expression. Try using this instead:

var pattern = new RegExp(w, 'i');

Hope this helps!

Thank you!!
After understanding diferences between string and Regular Expresions, I finish my exercise correctly.