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:
- 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:
Hello world, how are you doing?
Assumptions:
originalString
can be of different string lengthsstring1
is maxed at 15 charactersstring2
is maxed at 10 charactersstring3
is maxed at 10 characters- first 15 characters for the
originalString
would beHello 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?
3
Answers
I solved this by separating the original string into separate words and incrementally checking the length as I built each string. It works with your example, but could fail if there were some longer words or other written language quirks. I created an array,
strings
to build each string and indicate its maximum length.The following will get you what you want:
The breaks will only be done before whitespace characters and never inside a word.
I haven’t tested it for different strings and different line lengths, but you could start from here…