웃웃웃웃웃
웃웃웃웃웃

Reputation: 362

how to check entered regex pattern and example are correct or not

I have two textbox in my form. First for regex pattern, and second is for input text.

I am try to check enter regex pattern and entered text matches or not.

This is my simple attempt.

And this is working demo:

'01-01-2012'.match( /\d{2}-\d{2}-\d{4}/ )

Fiddle

Any solution for my query?

Upvotes: 0

Views: 251

Answers (2)

Gene D.
Gene D.

Reputation: 311

Use var pattern = new RegExp($('#pattern').val());. In this case you have to enter pattern without slashes, like \d{2}-\d{2}-\d{4} (or you can make a check for their presence and cut them).

Though you can create regexp in your code like var pattern = /\d{2}-\d{2}-\d{4}/, but when you get a pattern from the input field and assign it to a variable, JavaScript will not parse it as a regular expression, it just will assign a string to a variable. And because of this you have to explicitly create a RegExp object and pass this string to its constructor, so interpreter will create regular expression from it.

Upvotes: 1

SpaceDog
SpaceDog

Reputation: 3269

The match() on string takes a regexp object, however you are passing in a string. This will be converted to a regexp, unfortunately it will process the string some what, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FRegExp

If you enter \\d{2}-\\d{2}-\\d{4} in the text box it will work.

If you need the system to work with normal regular expressions you need to process the string and remove the / at either end and then escape the \.

Upvotes: 0

Related Questions