如何将Discord表情数组分割为单表情不拆分的100字符内子数组
Solution to Group Discord Emojis Without Splitting Elements
Got it, the problem with using match(/.{1,100}/g) here is that it doesn't respect the boundaries of your individual emoji elements—it just blindly splits the combined string at the 100-character mark, which breaks emojis right in the middle. Here's a straightforward, element-safe way to group your emojis so each group's combined length stays under 100 characters:
JavaScript Implementation
const emojis = [ '<:cmd:409342761179938838>', '<:nobot:409342761246916610>', '<:haha:409342761272344578>', '<:rrrr:409342761431728139>', '<:aaa:409342761439854593>', '<:fff:409342761503031296>', '<:woah:409342761532391424>', '<:swon:409342761549037568>', '<:owoah:409342761595043850>', '<:sss:409342761662414848>' ]; const maxAllowedLength = 100; const groupedEmojis = []; let currentGroup = []; let currentGroupLength = 0; for (const emoji of emojis) { // Calculate how much length this emoji adds (include a space if group isn't empty) const lengthToAdd = currentGroup.length > 0 ? emoji.length + 1 : emoji.length; if (currentGroupLength + lengthToAdd <= maxAllowedLength) { // Add emoji to current group and update total length currentGroup.push(emoji); currentGroupLength += lengthToAdd; } else { // Finalize current group, add to results, start new group with this emoji groupedEmojis.push(currentGroup.join(' ')); currentGroup = [emoji]; currentGroupLength = emoji.length; } } // Don't forget to add the last remaining group if (currentGroup.length > 0) { groupedEmojis.push(currentGroup.join(' ')); } console.log(groupedEmojis);
How This Works
- We keep track of the current group of emojis and the total character length of that group when joined with spaces.
- For each emoji, we calculate exactly how much length it would add to the current group (including a leading space if the group isn't empty).
- If adding the emoji keeps the total length under 100, we add it to the current group and update the length counter.
- If adding it would exceed the limit, we turn the current group into a space-separated string, add it to our result array, and start a new group with the current emoji.
- Finally, we make sure to add the last group (which might not have hit the length limit) to the results.
Running this code will give you exactly the grouped output you're looking for:
[ '<:cmd:409342761179938838> <:nobot:409342761246916610> <:haha:409342761272344578>', '<:rrrr:409342761431728139> <:aaa:409342761439854593> <:fff:409342761503031296>', '<:woah:409342761532391424> <:swon:409342761549037568> <:owoah:409342761595043850>', '<:sss:409342761662414848>' ]
内容的提问来源于stack exchange,提问作者D.Lene
相关产品推荐
相关产品推荐

