I am getting regex
string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.
But even if i pass valid input text it does not pass regex
condition
code :
var pattern = "/^[A-Za-z\s]+$/";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
Fiddle :- http://jsfiddle.net/wn9scv3m/
To create a regex from string variables in JavaScript, we can use a new RegExp object to pass a variable as a regex pattern: Copied to clipboard! The RegExp object takes in the regular expression as the first argument, while for the second argument, we can pass flags to be used with the expression, such as:
Using the RegExp Object. In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
to convert the pattern string to a regex object with the RegExp constructor. Then we can call re.test to check if value matches the re regex pattern. Therefore, match is true since value matches the pattern, which is an email regex.
Using String Methods. In JavaScript, regular expressions are often used with the two string methods: search () and replace (). The search () method uses an expression to search for a match, and returns the position of the match. The replace () method returns a modified string where the pattern is replaced.
Two problems:
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/
As far as I can see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions you are combining two methods to declare RegExp. If you are using the string variant, then don't include the "/" character before and after the expression, example:
var pattern = "^[A-Za-z\s]+$";
pattern = new RegExp(pattern);
If you like the /regexp/ form better, then use it without quotes:
pattern = /^[A-Za-z\s]+$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With