Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript syntax for regex using variable as pattern

I have a variable patt with a dynamic numerical value

var patt = "%"+number+":"; 

What is the regex syntax for using it in the test() method?

I have been using this format

var patt=/testing/g; var found = patt.test(textinput); 

TIA

like image 864
Jamex Avatar asked Oct 12 '11 04:10

Jamex


People also ask

Can you use variable in regex JavaScript?

Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .

Can I put variable in regex?

There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.

How do I match a pattern in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


1 Answers

Yeah, you pretty much had it. You just needed to pass your regex string into the RegExp constructor. You can then call its test() function.

var matcher = new RegExp("%" + number + ":", "g"); var found = matcher.test(textinput); 

Hope that helps :)

like image 119
MicronXD Avatar answered Sep 20 '22 10:09

MicronXD