-2

I want to find an occurrence of a word in a long string. This word changes with every iteration of the for loop:

array_word = '....'

for(var i.........) {
    var regex=new RegExp('/.*'+array_word[i]+'.*/');

    if(regex.test(array_word[i]) {
        return true;
    }
}

The problem could be that I used the wrong regex because the program doesn't return true, can anyone help me?

SidOfc
  • 4,552
  • 3
  • 27
  • 50
furie
  • 3
  • 3

1 Answers1

1

You don't need to use forward slashes.

var regex = new RegExp('.*'+array_word[i]+'.*');

.* won't be needed for this case.

var regex = new RegExp(array_word[i]);

From the docs,

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • This is very much true, when building a regex through the `new RegExp` constructor you can actually pass it as a string which essentially allows you to "build" your regex :) – SidOfc Nov 16 '15 at 15:17
  • Actually, I do not see the point in keeping `.*` in the pattern. It is not Java :) – Wiktor Stribiżew Nov 16 '15 at 15:23
  • May be op wants to use the compiled RegExp object for some purposes other purposes also. OH , for this `var regex = new RegExp(array_word[i]);` would be enough since he's using `test` func – Avinash Raj Nov 16 '15 at 15:24
  • But I don't find the logic in op's code. – Avinash Raj Nov 16 '15 at 15:27