Help with String.match()

Help with String.match()
0

#1

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!!


#2

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


#3

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!


#5

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