'Discord.js get 2nd mention

I have this command where I want to get the 2nd mention (Role2).

!command [Role1] [Role2]

I know that I can get the first role with this code:

const role1 = message.mentions.roles.first();

But I couldn't find anything for the 2nd mention, nor could anyone tell me how to do it. I hope anyone can help me with this issue.



Solution 1:[1]

message.mentions.roles is a Collection, and that has a .at() method.

const role2 = message.mentions.roles.at(1) // index 1 is the second value

Note the roles may not be in the right order, so it's a good idea to use regex, and map by getting from cache

// import MessageMentions class from discord.js module
const roles = message.content.match(MessageMentions.ROLES_PATTERN).map(r => message.guild.roles.cache.get(r.slice(3, r.length - 1))
const role2 = roles[1]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrMythical