Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert regex string to regex object in javascript

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/

like image 301
Shaggy Avatar asked Aug 27 '14 08:08

Shaggy


People also ask

How to create a regex from string variables in JavaScript?

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:

What is a regexp object in JavaScript?

Using the RegExp Object. In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

How to convert a string to a regex in Python?

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.

What are the methods of regular expressions in JavaScript?

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.


2 Answers

Two problems:

  • You need to escape the backslash.
  • You need to remove the forward slashes on the beginning and end of string.

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/

like image 92
parchment Avatar answered Sep 24 '22 13:09

parchment


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]+$/;
like image 35
BogdanBiv Avatar answered Sep 21 '22 13:09

BogdanBiv