Steve
Steve

Reputation: 4908

Unable to use search() with a variable pattern

I have a jsfiddle here - http://jsfiddle.net/stevea/mrQEz/1/ - where I'm having trouble using the JavaScript search() function with a variable pattern.

The code searches div.answer for the word you enter into the filter field. I want the search to be case insensitive so I want to get the "i" flag at the end of the search pattern. If I directly enter /background/i as the search pattern, in line 9 of the JavaScript, I find "Background" fine in the text. But if I enter "background" in the filter field and try to build the search pattern from

term = "/" + this.value + "/i";

it doesn't work, even though term seems to have the right thing in it: /background/i.

Does anyone see the problem? Thanks.

Upvotes: 1

Views: 58

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149050

There are two ways of creating regular expressions in JavaScript. The first is the literal syntax:

term = /background/i;

But if you would like to convert a string to a regular expression, you need to call the RegExp constructor:

term = new RegExp(this.value, "i");

You can see it working here.

Upvotes: 6

Related Questions