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.
  • 28,965
  • 14
  • 72
  • 87
zahmis
  • 27
  • 5

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
  • 323,592
  • 20
  • 270
  • 324
1

try using a dynamically generated Regex:

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