Modifying the regex pattern at runtime

R

Robert Oschler

One of the things that has always thrown me about Javascript regular
expression patterns, is that you don't include quotes around them. So how
can I modify a regex pattern at runtime. For example, given:

var regexPattern = /.*?\s/i;

Suppose I want to change the whitespace character to a comma, based on a
variable being true or false?

// This doesn't work, the string var double-quotes cause the match() method
to find nothing.
var delimChar = "/s";

if (commaDelimited)
delimChar = ",";

var regexPattern = "/.*?" + delimChar + "/i";

var matches = theString.match(regexPattern);

So what is the proper syntax?

Thanks.
 
M

michael elias

You can use the RegExp object to create a regular expression from a
string.

var oRegExp = new RegExp("pattern");

var aMatched = sString.match(oRegExp);
 
R

Robert Oschler

michael elias said:
You can use the RegExp object to create a regular expression from a
string.

var oRegExp = new RegExp("pattern");

var aMatched = sString.match(oRegExp);

Michael,

Thanks! That does it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top