JavaScript Text Wrap/Fold On Specific Line-Character-Length

function fold(input, max_line_character_length, fold_character){
  var regex;

  input                      = "string" === typeof input                      ? input                        : "";
  max_line_character_length  = "number" === typeof max_line_character_length  ? max_line_character_length    : 10;
  fold_character             = "string" === typeof fold_character             ? fold_character               : "\n";

  regex = new RegExp("(.{"  +  String(max_line_character_length - fold_character.length)  +  "})", "gim");
  
  return input.replace(regex, "$1" + fold_character);
}

running

fold("aawregawaergarewqagaeragaewrgaewarjuasciji23r4avasdfaba asafdav fdsaewtyaa34a5a42aaa 6a2345aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 20)

will transform aawregawaergarewqagaeragaewrgaewarjuasciji23r4avasdfaba asafdav fdsaewtyaa34a5a42aaa 6a2345aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" into:

aawregawaergarewqag
aeragaewrgaewarjuas
ciji23r4avasdfaba a
safdav fdsaewtyaa34
a5a42aaa 6a2345aaaa
aaaaaaaaaaaaaaaaaaa
aaaaaaaaaa

specifying “closing character” – on unix or “original” [unformatted] email template, you might notice that the character before the new-line, is sometimes ‘=‘,
here too, you can specify (instead of default \n) any set of characters:

running

fold("aawregawaergarewqagaeragaewrgaewarjuasciji23r4avasdfaba asafdav fdsaewtyaa34a5a42aaa 6a2345aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 20, "=\n")

will transform the text into

aawregawaergarewqa=
gaeragaewrgaewarju=
asciji23r4avasdfab=
a asafdav fdsaewty=
aa34a5a42aaa 6a234=
5aaaaaaaaaaaaaaaaa=
aaaaaaaaaaaaaaaa

– max length is set to the limit given — INCLUDING the wrap character! (not including the \n).
– you should specify \n if you want to wrap the string [otherwise it is just a “separator-function” separating with delimiter every X characters…]

– it should pretty much support every charset, but you might consider transforming the string into byte-string first.

for example this seems to work fine:

fold("אאאאאאאאבבבבבבבבגגגגגגדדדדדדדדדדההההההההווווווווו", 10, "=\n")
outputs...
"אאאאאאאא=
בבבבבבבב=
גגגגגגדד=
דדדדדדדד=
הההההההה=
וווווווו=
ו"

you can make sure max-character value is less than 256 using unescape(encodeURIComponent("YOUR TEXT HERE"))

you better convert stuff before… for example to BASE64, than use the fold function on the ASCII content…

******
b.t.w
although it works it sure looks weird.. each line will look like אאאא=..
******