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
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() .
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.
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 "@" .
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With