From fbcbb29884a35308a7af2169f5f9ae5658c458e8 Mon Sep 17 00:00:00 2001 From: u9g <43508353+u9g@users.noreply.github.com> Date: Thu, 10 Jun 2021 05:24:45 -0400 Subject: [PATCH] feat(Util): allow array for StringOptions' char (#5566) Co-authored-by: Voltrex <62040526+VoltrexMaster@users.noreply.github.com> Co-authored-by: SpaceEEC Co-authored-by: Papaia <43409674+papaia@users.noreply.github.com> Co-authored-by: Noel --- src/structures/interfaces/TextBasedChannel.js | 3 ++- src/util/Util.js | 16 ++++++++++++++-- typings/index.d.ts | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/structures/interfaces/TextBasedChannel.js b/src/structures/interfaces/TextBasedChannel.js index 34fba43f3..11af71255 100644 --- a/src/structures/interfaces/TextBasedChannel.js +++ b/src/structures/interfaces/TextBasedChannel.js @@ -102,7 +102,8 @@ class TextBasedChannel { * Options for splitting a message. * @typedef {Object} SplitOptions * @property {number} [maxLength=2000] Maximum character length per message piece - * @property {string} [char='\n'] Character to split the message with + * @property {string|string[]|RegExp|RegExp[]} [char='\n'] Character(s) or Regex(s) to split the message with, + * an array can be used to split multiple times * @property {string} [prepend=''] Text to prepend to every piece except the first * @property {string} [append=''] Text to append to every piece except the last */ diff --git a/src/util/Util.js b/src/util/Util.js index 75cfad3ae..9df2f0935 100644 --- a/src/util/Util.js +++ b/src/util/Util.js @@ -64,8 +64,20 @@ class Util { static splitMessage(text, { maxLength = 2000, char = '\n', prepend = '', append = '' } = {}) { text = Util.verifyString(text, RangeError, 'MESSAGE_CONTENT_TYPE', false); if (text.length <= maxLength) return [text]; - const splitText = text.split(char); - if (splitText.some(chunk => chunk.length > maxLength)) throw new RangeError('SPLIT_MAX_LEN'); + let splitText = [text]; + if (Array.isArray(char)) { + while (char.length > 0 && splitText.some(elem => elem.length > maxLength)) { + const currentChar = char.shift(); + if (currentChar instanceof RegExp) { + splitText = splitText.map(chunk => chunk.match(currentChar)); + } else { + splitText = splitText.map(chunk => chunk.split(currentChar)); + } + } + } else { + splitText = text.split(char); + } + if (splitText.some(elem => elem.length > maxLength)) throw new RangeError('SPLIT_MAX_LEN'); const messages = []; let msg = ''; for (const chunk of splitText) { diff --git a/typings/index.d.ts b/typings/index.d.ts index 4df55c233..d6c556324 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -3631,7 +3631,7 @@ declare module 'discord.js' { interface SplitOptions { maxLength?: number; - char?: string; + char?: string | string[] | RegExp | RegExp[]; prepend?: string; append?: string; }