-3
/^([A-Za-z0-9]){1,8}$/ 

This is a normal way to write a regex in JavaScript but I want to construct the regex dynamically with a variable in between ().

Variable = [A-Za-z0-9]

j08691
  • 204,283
  • 31
  • 260
  • 272
Abhishek
  • 1
  • 1

1 Answers1

5

This is how you can build a new regular expression from string:

var v = '[A-Za-z0-9]';
var regExp = new RegExp('^(' + v + '){1,8}$');
console.log(regExp);

Now you can use the regular expression regExp in your purpose

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32