-1

How can I make a function that splits a multiline string every nth character. I have the below function, but it doesn't work correctly with multiline strings.

splitIntoChunks("abab", 2) works correctly and gives ["ab", "ab"]

But, this doesn't work correctly:

var str = `aaa
bbb
ccc
ddd`

splitIntoChunks(str, 2)

This returns ["aa", "a", "bb", "b", "cc", "c", "dd", "d"]

And what I need is:

["aa" ["a\n", "bb", "b\n", "cc", "c\n", "dd", "d\n"]]

It needs to keep the \n

function splitIntoChunks(str, size) {
  return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072

1 Answers1

0

. doesn't match newlines by default. You can make it so by adding the s flag:

function splitIntoChunks(str, size) {
  return str.match(new RegExp('.{1,' + size + '}', 'gs'));
}


var str = `aaa
bbb
ccc
ddd`

console.log(splitIntoChunks(str, 2));
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
  • Thank you, this solved my problem. Will mark as answer when stack overflow lets me :) – user14844636 Dec 17 '20 at 14:44
  • Could you explain a bit more about the difference between the s and the m flag if possible, please? – user14844636 Dec 17 '20 at 14:46
  • `s` causes `.` to match newlines. `m` makes `^` and `$` match the start and end of a line instead of the the start and end of the whole string. E.g. with `foo\nbar` , `/^foo$/m` would match but `/^foo$/` wouldn't (because `$` matches the end of the whole string). – Felix Kling Dec 17 '20 at 15:01