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:
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 charactersoriginalString
would be Hello world, ho
w are you
doing?
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?
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));