s_p
s_p

Reputation: 4693

limit carriage return in string

I am getting the number of carriage return in a string like so

var str = str.split(/\n/).length;

I would like to limit my string so that after 5 cr's the string removes only those carriage returns after the max allowed. Can anyone lend a hand on the syntax for this.
Thank you, heres my attempt.


this flattens the entire string after 5, I would like to retain the first 5 then flatten then string

function countLineBreaks(str){
    var n = str.split(/\n/).length;
        return n;
};
var n = countLineBreaks(myStr);

if(n > 5)
    str = str.replace(/\n/g, " ");// replace cr's with empty space after 5

Upvotes: 1

Views: 91

Answers (2)

Xymostech
Xymostech

Reputation: 9850

You might be able to do it with regexes, but you can also just do it with splitting and joining:

var split = str.split("\n");
var first6 = split.splice(0, 6); // remove first 6 elements into first6
var result = first6.join("\n") + (split.length ? " " + split.join(" ") : "");

Upvotes: 3

DougM
DougM

Reputation: 2888

Split the array, merge all items after 5, and then join it back in.

function trimString(str) {
  var lines = str.split(/\n/);
  if(lines.length > 5) {
    var rest = lines.slice(5);
    lines.length = 5;
    lines[5] = rest.join(' ');
  }
  return lines.join('\n');
}

Upvotes: 2

Related Questions