0

My regular expression is /^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/ and in html I added it as a hidden element with the value of the element set to the above pattern

When I do this:

var regex = /^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/ 
var text = $(this).val()

and then test with regex.test(text) it works fine.

but when I assign regex like this:

var regex = $("#m"+id).val() // (my hidden element)

then it doesnt work. I have tried assigning it using new RegExp as well but also not working.I think it's doing it because it's returning the value as a string from $("#m"+id).val() (I am getting the right value returned here), but not sure what to parse it to.

Any help would be appreciated.

3 Answers 3

1

If you want to build regexp from string, then use Constructor of RegExp class, it takes string without slashes, so you should remove them. .slice(1, -1) removes first and last charecters. Try to use this:

var regex = new RegExp($("#m"+id).val().slice(1, -1));
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

var regex = new RegExp($("#m"+id).val())

Comments

0

The slashes at the beginning and the end are only used when it is a regex literal. Remove them to get the actual regular expression, then you can use new RegExp(str) to turn the string into a regex object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.