JavaScript Ninja - Wrap Fold Text At Certain Column Size

Posted at

You might be a *nix savvy, and already familiar with fold -w 80 [text file name] that will wrap
(a.k.a fold, a.k.a insert a line-break, a.k.a insert new-line)
your text to constant line length,

In server-side, it is very useful for stuff such as base64-content-cutting, for raw email template,
I'm using it as a quick -no-file-no-copy-from-bash- needed for deciphering spam emails before reporting them to SpamCop just to make sure they do not have any evil details that will later be used to reverse-track the customers (helping IT Security)

---- insert regular expression magic here ---------- :)

"kjlahflkjhweoiurysjfdhglkasjhfdoiuyewqdiufyalksjkjhalkjshdlkajhfdlkjahdsflkjahdsflkjhsadflkjhsadlkfjhsadlkfjhasdlkjfhalkdjfhhflkytiuwyretlkjahsdflkjhsadlkfhabcdefghij".replace(/(.{73})/gm,"$1\
")


this will trimmmmmmmm the text at (included) column 73 (after 73 characters)

"kjlahflkjhweoiurysjfdhglkasjhfdoiuyewqdiufyalksjkjhalkjshdlkajhfdlkjahdsf
lkjahdsflkjhsadflkjhsadlkfjhsadlkfjhasdlkjfhalkdjfhhflkytiuwyretlkjahsdfl
kjhsadlkfhabcdefghij"


integrate it using some prototype fun:
String.prototype.fold = function fold(wrap_at_N_column){
return this.replace(
new RegExp("(.{" + wrap_at_N_column + "})", "gm")
, "$1\
"
);
};


yeah I know I could have created the regex once and assign it to the String prototype itself as an "object bank",
but THAT IS NOT A GOOD PROGRAMMING ("mystery factor") - better recreate that object, or alternatively be open to get it so user could assign it itself (possibly reuse same object)

String.prototype.fold = function fold(wrap_at_N_column, regex){
regex = ("object" === regex &&
"function" === typeof regex.constructor &&
"string" === typeof regex.constructor.name &&
"regexp" === regex.constructor.name.toLowerCase() ) ? regex : new RegExp("(.{" + wrap_at_N_column + "})", "gm");

return this.replace(regex, "$1\
");
};



b.t.w there is no need to reassure that wrap_at_N_column is valid, it is already normalized by the regular-expression implementation (for example try -1 and such..) :]