javascriptstringsubstringstring-length

How to break up string based on specific length after finding the whitespace nearest to the character limit?


I have to break up a string field into multiple string fields if the original string exceeds a specific character limit. The original string can be of different lengths but the additional fields like string2, and string3 have a max character length of 10.

Question:

  1. How can I break up a single string field into multiple string fields with defined character limits based on the nearest whitespace to the character limit?

Example:

  1. Hello world, how are you doing?

Assumptions:

What I tried that didn't work:

let originalString = `Hello world, how are you doing?`
if(originalString.length > 15) {
  let string1 = originalString.substring(0,15) // this returns `Hello World,`
  let string2 = ???? // stuck here - need help
  let string3 = ???? // stuck here - need help
}

Expected output:


Solution

  • The following will get you what you want:

    The breaks will only be done before whitespace characters and never inside a word.

    const originalString = `Hello world, how are you doing?`,
          res=originalString.match(/(.{1,15})\s+(.{1,10})\s+(.{1,10})(?:\s+.|$)/);
    console.log(res.slice(1));