116

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 don't know how to pass variable in match command. Please help. Thank you.

Munawir
  • 3,346
  • 9
  • 33
  • 51
mesnicka
  • 2,458
  • 8
  • 23
  • 31
  • 1
    Exact duplicate of [How do you pass a variable to a Regular Expression JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression-javascript). Search more ;) – Dan Dascalescu Apr 04 '14 at 01:46
  • One more thing: If you are using a variable to construct an regexp, cares should be taken that the variable might contain regexp special characters. e.g. if you pass "c++", the regex compiler will complain `SyntaxError: Invalid regular expression: /c++/: Nothing to repeat` – dotslashlu Dec 19 '16 at 03:37

7 Answers7

241

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
  • 9,082
  • 3
  • 27
  • 33
  • 2
    +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";` – Christian C. Salvadó Jul 03 '10 at 22:42
17

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
  • 4,567
  • 24
  • 24
  • 4
    You get a imaginary downvote for using w3schools instead of MDN! https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp – flaky Jul 22 '16 at 06:32
9

Example. To find number of vowels within the string

var word='Web Development Tutorial';
var vowels='[aeiou]'; 
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
9

For example:

let myString = "Hello World"
let myMatch = myString.match(/H.*/)
console.log(myMatch)

Or

let myString = "Hello World"
let myVariable = "H"
let myReg = new RegExp(myVariable + ".*")
let myMatch = myString.match(myReg)
console.log(myMatch)
Driton Haxhiu
  • 117
  • 1
  • 6
  • it is helpful but when i use let myString = "Tata Nexon EV Tata" let myVariable = "Tata" let myReg = new RegExp("\b"+myVariable , "g") let myMatch = myString.match(myReg) console.log(myMatch) not working – Arindam Sarkar Jun 02 '22 at 14:34
0

for me anyways, it helps to see it used. just made this using the "re" example:

var analyte_data = 'sample-'+sample_id;
var storage_keys = $.jStorage.index();
var re = new RegExp( analyte_data,'g');  
for(i=0;i<storage_keys.length;i++) { 
    if(storage_keys[i].match(re)) {
        console.log(storage_keys[i]);
        var partnum = storage_keys[i].split('-')[2];
    }
}
geekbuntu
  • 851
  • 6
  • 4
0

Below is an example of a simple and effective way to mock 'like' operator in JS. enjoy!

const likePattern = '%%i%%%%%a';
const regexp = new RegExp(likePattern.replaceAll('%','.*'),"i");
console.log("victoria".match(regexp));
adB
  • 41
  • 4
-5
xxx.match(yyy, 'g').length
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 5
    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. – Christian C. Salvadó Jul 03 '10 at 22:36