Javascript: Variables Within Regex?
Javascript, Regular Expressions February 15th, 2009Is it possible to use a variable within a regular expression declaration? For example:
This doesnt return a result since findthis is being interpreted as text rather than a variable. I want its contents to be inserted into the regex expression.
var findThs="test123";
var mystring = "This is some test123 text";
var result = myString.match(/findthis(?:,| |$)/);
This doesnt return a result since findthis is being interpreted as text rather than a variable. I want its contents to be inserted into the regex expression.
Your best bet is to create the regex before you use it.
var myregex = new RegExp(findthis + "(.*)$")
but make sure that findthis does not contain any regex characters like ‘;.’