Skip to content

Instantly share code, notes, and snippets.

@vutranHS
Last active December 19, 2018 09:50
Show Gist options
  • Save vutranHS/cfee090719d056d39a17ccb2188367cd to your computer and use it in GitHub Desktop.
Save vutranHS/cfee090719d056d39a17ccb2188367cd to your computer and use it in GitHub Desktop.
Split String
function chunkString(str, splitSize = 50) {
const maxChunkedPart = 9999999999999999;
if (typeof str !== 'string') {
throw "str must be a string";
}
if (str.length <= splitSize) {
return str;
}
const trimedString = str.replace(/\s+/g," ");
const chunkedString = trimedString.match(new RegExp('.{1,' + splitSize + '}', 'g')) // split into limit 50 character.
const result = [];
const splitBySpace = trimedString.split(" ");
splitBySpace.forEach((word) => {
if (word.length >= 50) {
throw "invalid string";
}
});
let reservedString = null;
const resultArrayLength = chunkedString.length;
for (let i = 1; i <= resultArrayLength; i += 1) {
result.push(i.toString() + "/" + resultArrayLength.toString());
if (reservedString !== null) {
result[i-1] += ` ${reservedString}`;
}
while (splitBySpace.length > 0) {
const word = splitBySpace.shift();
if (word) {
const newWord = result[i-1] + ` ${word}`;
if (newWord.length <= splitSize) {
result[i-1] = result[i-1] + ` ${word}`;
reservedString = null;
} else {
reservedString = word;
break;
}
}
}
}
return result;
}
const happyCase = chunkString("I can't believe Tweeter now supports chunking my messages, so I don't have to do it myself.", 50);
const badCase = chunkString("I can't believe Tweeter now supports chunking my messages, so I don't have to do it myself. ha", 50);
console.log(badCase);
const objectCase = chunkString({"obj": 1}, 10);
const stringShorterThanLimit = chunkString("I can't believe Tweeter now supports");
const whiteSpaceTrimmed = chunkString("I can't believe Tweeter now supports chunking my messages, so I don't have to do it myself. ", 50);
const invalidWords = chunkString("I can'tdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffieve Tweeter now supports chunking my messages, so I don't have to do it myself. ", 50);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment