Filter() Method Is Not Behaving Consistently

My project is found here:!/sprawlbotjs

The user ids in this post have been redacted.

I’ve attempted to follow the instructions here:

Instead of using: !Discord.MessageMentions.USERS_PATTERN; for the RegExp, I’m using: const usrRegEx = /<@!?(1|\d{17,19})>/g; though, I doubt that that’s the problem.

The code in question that’s giving me issues is the following:

let argsWithoutMentions = args.filter(arg => !usrRegEx.test(arg));

console.log("All Arguments: " + args)
console.log("Arguments No Users: " + argsWithoutMentions)

The command being issued each time in Discord is:s!roll2 <@!user1> <@!user2> <@!user3>

The output is giving inconsistent results, for example:

Console Output 1:

s!roll <@!user1> <@!user2> <@!user3>
All Arguments: <@!user1>,<@!user2>,<@!user3>
Arguments No Users: <@!user1>,<@!user3>

Console Output 2:

s!roll <@!user1> <@!user2> <@!user3>
All Arguments: <@!user1>,<@!user2>,<@!user3>
Arguments No Users: <@!user2>

The code has not changed and I am simply providing the same command twice.

Beyond all of this, “Arguments No Users” should actually remain an empty set.

Is this a problem with my code or an issue with Glitch?

Thank you for your time!

I believe this is an unfortunate side-effect of global RegExp’s lastIndex which stores state on the regex object. successive tests will use the last index as the start of the search, causing it to fail in most cases
one solution would be to use the regex literal directly instead of storing it in a variable. another solution would be to reset the .lastIndex property of the variable to 0 after each test. since you are writing the regex yourself, you can also remove the g global flag, which will also remove this behavior.


Using the literal worked!! The following now behaves as expected.

let argsWithoutMentions = args.filter(arg => !/<@!?(1|\d{17,19})>/g.test(arg));

Thank you so much for your help! There’s no way I would’ve gotten this.

1 Like