views:

45

answers:

3

Hello,

i found several similar questions, but it did not help me... so i have this problem:

var xxx = "victoria";
var yyy = "i";
alert(xxx.match(yyy/g).length);

I dont know how to pass variable in match command. Please help. Thank you.

A: 
xxx.match(yyy, 'g').length
SilentGhost
This will work *only* in Firefox, and it isn't even documented. The specification states that the [`String.prototype.match`](http://bclary.com/2004/11/07/#a-15.5.4.10) method expects only *one argument*. Using the `RegExp` constructor, as @Chris suggests is the preferred way.
CMS
+5  A: 

Although the match function doesn't accept string literals as regex patterns, you can use the constructor of the RegExp object and pass that to the String.match function:

var re = new RegExp(yyy, 'g');
xxx.match(re);

Any flags you need (such as /g) can go into the second parameter.

Chris Hutchinson
+1, this is the preferred way, BTW, if the argument passed to the `match` method is not a `RegExp` object, internally the `RegExp` constructor will be invoked using that value, so you can use a *string pattern*, e.g.: `"a123".match("\\d+")[0] === "123";`
CMS
A: 

You have to use RegExp object if your pattern is string

var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);

If pattern is not dynamic string:

var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);
Anpher