1

I would like to slice a javascript string into an array of strings of specified length (the lenght can vary), so I would like to have length parametr as a separete variable:

var length = 3;
var string = 'aaabbbcccddd';
var myArray = string.match(/(.{3})/g);

How to use length variable in match? Or any other solution similar to str_split in PHP.

My question is not a duplicate of: Split large string in n-size chunks in JavaScript cause I know how to slice, but the question is how to use variable in match.

I can't manage to do that Javascript Regex: How to put a variable inside a regular expression?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Tikky
  • 1,253
  • 2
  • 17
  • 36

2 Answers2

1

Well string.substr() is a better option if you always have to split by length only.

But in case you are curious to know how to do it with regex you can add variable in your RegExp by following way.

var length = 3;
let reg = new RegExp(`(.{${length}})`, 'g')
var string = 'aaabbbcccddd';
var myArray = string.match(reg);
console.log(myArray);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

I do not know whether you got a fix for the issue:

I had gone through your question Yesterday, but was not able to answer it because of the reason that the question was on hold or marked as duplicate and later I got a fix for this. Hope it helps you if you do not got it fixed yet.

What I have used is new RegExp(), please see the fiddle:

var length = 3;
var string = 'aaabbbcccddd';
dynamicRegExp =new RegExp("(.{"+length+"})", "g");
console.log("Regex used: "+ dynamicRegExp);
var myArray = string.match(dynamicRegExp);
console.log("Output: "+ myArray);

Syntax

new RegExp(pattern[, flags])
RegExp(pattern[, flags])

Parameters

  • Pattern

The text of the regular expression or, as of ES5, another RegExp object (or literal) to copy (the latter for the two RegExp constructor notations only).

  • flags

If specified, flags indicates the flags to add, or if an object is supplied for the pattern, the flags value will replace any of that object's flags (and lastIndex will be reset to 0) (as of ES2015). If flags is not specified and a regular expressions object is supplied, that object's flags (and lastIndex value) will be copied over.

What @Code Maniac is also correct or same as this one.

Sinto
  • 3,915
  • 11
  • 36
  • 70