Pankaj
Pankaj

Reputation: 10105

set dynamic pattern in Regexp

var txtpattern = '/[a-z]+/';
var regex = new RegExp(txtpattern);
var result = txtstring.match(regex); //returns null
var result = txtstring.match(/[a-z]+/); //returns some value

My query is, Is there any way to set the dynamic pattern in match arguments?

Upvotes: 1

Views: 4807

Answers (1)

Ivan
Ivan

Reputation: 10372

When using new Regex(), you need to remove the start and end / characters, like so:

var txtpattern = '[a-z]+';
var regex = new RegExp(txtpattern);
var result = txtstring.match(regex);

Upvotes: 7

Related Questions