0

I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.

For example if I do :

var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);

I get a string res = "alge": //thus verifying that alge exists in algeria

But if I do this, it returns null, why? and how can I make it work?

var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
fejese
  • 4,601
  • 4
  • 29
  • 36
Codious-JR
  • 1,658
  • 3
  • 26
  • 48

4 Answers4

3

To make a regex from a string, you need to create a RegExp object:

var regex = new RegExp("alge", "g");

(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)

Community
  • 1
  • 1
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • Was just typing the same. In the original post var regex = "/alge/g" is a string, not a regular expression :) – PeteAUK Jun 04 '14 at 14:38
0

You don't need quotes around the regex:

var regex = /alge/g;
akxlr
  • 1,142
  • 9
  • 23
0

Remove the quotes around the regex.

              var regex = /alge/g;
              var string = "algeria";
              var res = string.match(regex);
              alert(res);
Lynxy
  • 117
  • 2
  • 8
0

found the answer, the match function takes a regex object so have to do

             var regex = new RegExp(string, "g");
            var res = text.match(regex);

This works fine

Codious-JR
  • 1,658
  • 3
  • 26
  • 48