Variable inside RegEx

E

Er Galv?o Abbott

Greetings.

I have a function that does some pattern matching with JS's RegEx and
I'm trying to use a variable inside of it. Nothing that I've done
worked, so please help me.

Here is the func:

function validateField(formField,limit)
{
if (formField.match(/^\d{1,11}\,\d{2}$/))
{
return true;
}
}

What I need is to replace the "11" in the RegEx with the var limit.

How can I do this???

TIA,
 
M

Michael Winter

Greetings.

I have a function that does some pattern matching with JS's RegEx and
I'm trying to use a variable inside of it. Nothing that I've done
worked, so please help me.

Here is the func:

function validateField(formField,limit)
{
if (formField.match(/^\d{1,11}\,\d{2}$/))
{
return true;
}
}

What I need is to replace the "11" in the RegEx with the var limit.

How can I do this???

As you've no doubt discovered, literals cannot have variables in them.
However, the RegExp() constructor can:

function validateField( formField, limit ) {
var re = new RegExp( '^\d{1,' + limit + '}\,\d{2}$' );

return formField.match( re );
}

If you need to use flags, add them as a string as the second parameter.
Global, for example:

... = new RegExp( 'pattern', 'g' );

Hope that helps,
Mike
 
R

Richard Cornford

function validateField( formField, limit ) {
var re = new RegExp( '^\d{1,' + limit + '}\,\d{2}$' );
<snip>

But is necessary to escape the escape characters in the string literals
provided for the RegExp constructor, something like (untested):-

var re = new RegExp( '^\\d{1,' + limit + '}\\,\\d{2}$' );

Richard.
 
L

Lasse Reichstein Nielsen

if (formField.match(/^\d{1,11}\,\d{2}$/))

(no need to escape the comma)
What I need is to replace the "11" in the RegEx with the var limit.

If the regular expression isn't constant, you can't use the literal
notation, and must construct the regular expression using the RegExp
function instead.

RegExp("^\\d{1," + limit + "},\\d{2}$")

Notice that the argument to RegExp is a string literal, and as such
treats backslashes special. To include a backslash in the generated
regular expression, you must write two in the string literal.

/L
 
M

Michael Winter

<snip>

But is necessary to escape the escape characters in the string literals
provided for the RegExp constructor, something like (untested):-

[snipped example]

*Slaps forehead*

Quite right.

Mike
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top