Search code examples
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:

  • originalString can be of different string lengths
  • string1 is maxed at 15 characters
  • string2 is maxed at 10 characters
  • string3 is maxed at 10 characters
  • first 15 characters for the originalString would be Hello world, ho
  • next 10 characters would be w are you
  • next 10 character would be doing?
  • Do not break up whole words
  • only populate street2 and street3 if required. if all characters can fit into street1 and street2 then street3 can be empty

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:

  • originalString = Hello world, how are you doing?
  • string1 = Hello world,
  • string2 = how are
  • string3 = you doing?

Solution

  • The following will get you what you want:

    • the first string containing up to 15 characters
    • the second string containing up to 10 characters
    • the third string containing up to 10 characters

    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));