convert regex string to regex object in javascript
Use regex-parser
:
const parseRegex = require("regex-parser")
parseRegex("/^hi$/g")
// => /^hi$/g
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/