From 6b206457400ce31d566b02a0c135042afb540853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?A=2E=20Rom=C3=A1n?= Date: Sun, 3 Jul 2022 15:36:20 +0200 Subject: [PATCH] refactor(Util): make single `replace` call in `cleanContent` (#8210) Co-authored-by: Almeida --- packages/discord.js/src/util/Util.js | 47 ++++++++++++++-------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index a2a273707..3e3adea1c 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -474,6 +474,7 @@ function basename(path, ext) { const res = parse(path); return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0]; } + /** * The content to have all mentions replaced by the equivalent text. * @param {string} str The string to be converted @@ -481,32 +482,32 @@ function basename(path, ext) { * @returns {string} */ function cleanContent(str, channel) { - str = str - .replace(/<@!?[0-9]+>/g, input => { - const id = input.replace(/<|!|>|@/g, ''); - if (channel.type === ChannelType.DM) { - const user = channel.client.users.cache.get(id); - return user ? `@${user.username}` : input; - } + return str.replaceAll(/<(@[!&]?|#)(\d{17,19})>/g, (match, type, id) => { + switch (type) { + case '@': + case '@!': { + const member = channel.guild?.members.cache.get(id); + if (member) { + return `@${member.displayName}`; + } - const member = channel.guild.members.cache.get(id); - if (member) { - return `@${member.displayName}`; - } else { const user = channel.client.users.cache.get(id); - return user ? `@${user.username}` : input; + return user ? `@${user.username}` : match; } - }) - .replace(/<#[0-9]+>/g, input => { - const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, '')); - return mentionedChannel ? `#${mentionedChannel.name}` : input; - }) - .replace(/<@&[0-9]+>/g, input => { - if (channel.type === ChannelType.DM) return input; - const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, '')); - return role ? `@${role.name}` : input; - }); - return str; + case '@&': { + if (channel.type === ChannelType.DM) return match; + const role = channel.guild.roles.cache.get(id); + return role ? `@${role.name}` : match; + } + case '#': { + const mentionedChannel = channel.client.channels.cache.get(id); + return mentionedChannel ? `#${mentionedChannel.name}` : match; + } + default: { + return match; + } + } + }); } /**