Mohammed Aslam
Mohammed Aslam

Reputation: 1015

How to append regex literal with string literal in javascript

Can i append regex literal with string literal in javascript ? Like this:

var str = "iam 91 old";
var query = 'old';
var reg = /(\d+\s + query +)/;
alert(reg.exec(str)[1]);

this cod will be error.

Upvotes: 2

Views: 1289

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382514

Don't use a literal.

Use the RegExp constructor :

var reg = new RegExp("(\\d+\\s" + query + ")");

Upvotes: 3

Related Questions