Design & Download
Your JS Library
in Seconds!!!

Snippet: splitLines() - Array of Lines

Written by Christopher West (cwest) on December 05, 2015.
Turns a string with multiple lines into an array of strings where each string in the array is one of the lines.
function splitLines(str, opt_keepEnds) {
  var start = 0, ret = [], l;
  // Not using split because of IE8 error.
  str.replace(/\r\n?|[\n\x0B\x0C\x1C-\x1E\x85\u2028\u2029]/g, function(m, i) {
    l = m.length;
    ret.push(str.slice(start, opt_keepEnds ? i + l : i));
    start = i + l;
  });
  if (str = str.slice(start)) {
    ret.push(str);
  }
  return ret;
}

Python provides an excellent function called string.splitlines() which effectively turns a string into a list of strings. Now you can do the same thing in JavaScript using YourJS.splitLines(str, opt_keepEnds).

splitLines(...) API Documentation

Description

Turns a string with multiple lines into an array of strings where each string in the array is one of the lines.

Parameters

  1. str {string}:
    The string which will be split into an array of strings.
  2. opt_keepEnds {boolean=}:
    Optional. Defaults to false. If true the strings within the returned array will end in the character(s) which caused the line separation.

Returns

Returns an array of strings where each string is a separate line found in str. If the last line has nothing on it, it will not be included in the returned array.