0

I have this array ["Brad", "came", "to", "dinner", "with", "us"]

Brad came to dinner with us (27 chars > 16) so I need to split it into 2 strings:

Brad came to
dinner with us

Words cannot be sliced

let inpt=["Brad", "came", "to", "dinner", "with", "us"]
op=[]
for(i of inpt) if (op.join('').length+i.length <16) {op.push(i)} else break
console.log(op.join(' '))

This return me first part but how can I get second and others if my input array(string) would be longer then 16+16+16....

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • 2
    Hi, perhaps start appending to a new list once the limit is reached? – IronMan Nov 04 '20 at 20:57
  • Very similar question: [Split string at space after certain number of characters in Javascript](https://stackoverflow.com/q/49836558/215552) – Heretic Monkey Nov 04 '20 at 21:02
  • Does this answer your question? [Splitting a string based on max character length, but keep words into account](https://stackoverflow.com/questions/58204155/splitting-a-string-based-on-max-character-length-but-keep-words-into-account) – Heretic Monkey Nov 04 '20 at 21:02

2 Answers2

3

After joining by spaces, use a regular expression to match up to 16 characters, followed by a space or the end of the string:

let inpt=["Brad", "came", "to", "dinner", "with", "us"];
const str = inpt.join(' ');
const matches = str.match(/.{1,16}(?: |$)/g);
console.log(matches);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Can also be done via Array.reduce:

let inpt=["Brad", "came", "to", "dinner", "with", "us"];

let out = inpt.reduce((acc, el) => {
  let l = acc.length;
  if (l === 0 || (acc[l - 1] + el).length > 15) {
    acc[l] = el;
  } else {
    acc[l - 1] += " " + el;
  }
  return acc;
}, []);

console.log(out);
James
  • 20,957
  • 5
  • 26
  • 41