0

I'm trying to split a string every n characters using a match function, but I figured that there are other uses to using a variable in a match function.

I know that the code

str.match(/.{0,3}/g);

will give me every three characters in a string, but

var n = 3;
str.match(/.{0,n}/g);

will not.

  • 2
    You can always construct regular expressions with [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). – Sebastian Simon Mar 14 '17 at 16:31
  • 1
    is [that](http://stackoverflow.com/questions/3172985/javascript-use-variable-in-string-match) the answer you were searching for ? – BadPoussin Mar 14 '17 at 16:32
  • Possible duplicate of [How do you use a variable in a regular expression?](http://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – Sebastian Simon Mar 14 '17 at 16:36

1 Answers1

4
var n = 3;
str.match(new RegExp(".{0," + n + "}", "g"));
Trevor
  • 13,085
  • 13
  • 76
  • 99