0

The following regex check is not working in the code. But if i use this pattern at regex101.com it works perfectly

var pattern = "^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*@([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$";
var value = "[email protected]";

var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
  	alert("Failed");
} else {
	alert("passed");
}

Could you please help me why this is happening here. By the way if i make some modifications like given below, it works. But i want it to work with (new RegExp(pattern))

var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*@([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "[email protected]";

if (!pattern.test(value)) {
  	alert("Failed");
} else {
	alert("passed");
}

2
  • 1
    But i want it to work with (new RegExp(pattern) Why? Commented Nov 4, 2016 at 3:40
  • @torazaburo got the answer.. I need to add extra backslash in regular expression infront of each backslash. because "new regExp(pattern)" was stripping backslashes from the pattern and thats why it was not working. Commented Nov 7, 2016 at 0:49

2 Answers 2

3

Just remove the double quotes and put your Regex simply in forward slashes.

var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*@([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "[email protected]";

var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
  	alert("Failed");
} else {
	alert("passed");
}

It's because, if you're putting double quotes, then you need to escape your regular expression

However, you can simply put your regular expression as it is when placing it between forward slashes.

Sign up to request clarification or add additional context in comments.

1 Comment

But if we have to do it with a quote ?as in actual code this regex is coming from a json object.
0

You need to escape those backslashes (\).

var pattern = "^([a-zA-Z0-9]([-\\.\\w]*[a-zA-Z0-9])*@([a-zA-Z0-9][-\\w]*[a-zA-Z0-9]\\.)+[a-zA-Z]{2,9})$";
var value = "[email protected]";

var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
  	console.log("Failed");
} else {
	console.log("passed");
}

3 Comments

@torazaburo He need explanation why it is not working with RegExp.
@torazaburo from the question: "But i want it to work with (new RegExp(pattern))"
@torazaburo OP Said: why this is happening here. Clearly he wanted an explanation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.