0

I'm struggling with a very simple problem.

lines = "hogefoobarwai"

I want to cut this string into 4 characters.

Like this.

hoge, foob, arwa, i

How to split?

I try to use split() with regex.

let vars = lines.match(/.{4}/g);

This is good. But if something like {4} is variable, it won't work.

for example

 length = 6

let vars = lines.match(/.{length}/g);

this shows literally /.{length}/.

If anyone can tell me what it is, please let me know.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
zahmis
  • 27
  • 6

2 Answers2

1

You could take a minimum length of one (for getting smaller substrings) and the length and build a new regular expression.

const
    lines = "hogefoobarwai",
    length = 4,
    parts = lines.match(new RegExp(`.{1,${length}}`, 'g'));

console.log(parts);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

try using a dynamically generated Regex:

const newRegEx = new RegEx('{' + length + '}', g)

Murilo Schünke
  • 106
  • 2
  • 7