0

I'm trying to get list of users from string.

EXAMPLE

What I want:

String: "Hello, @alice"

I got users arr: ["alice"]

My code:

export const getRecepientsArrFromMessage = (value: string): string[] | [] => {
  if (value) {
    const REGEX = /(^@)([\wа-я]|@|.)/gi
    return value
      .trim()
      .split(' ')
      .filter((el) => el.length > 0 && REGEX.test(el))
      .map((el) => el.slice(1, el.length))
  }
  return []
}

What I got:

If my string is: Hello @user1 @user2 @user1@sdf.com @user2 @user1 @user1 @user2

I got users only through one: ['@user1', '@user1@sdf.com', '@user1', '@user2']

What is wrong here?

I tried different variations of the regular expression, but the answer remained the same

Vitaliy
  • 1
  • 1
  • Remove the `g` flag: `const REGEX = /(^@)([\wа-я]|@|.)/i` – Unmitigated Mar 25 '23 at 08:37
  • @Unmitigated Thanks! Looks that it works fine. What the problem with 'g'? I have array of words and check each word with this regex. Logically, the presence or absence of the flag should not affect the result. – Vitaliy Mar 25 '23 at 08:40
  • @Vitaliy Regexes with the global flag are stateful. When calling `RegExp#test`, it will update the regular expression object's lastIndex property and the next time, it will only start matching from this lastIndex. – Unmitigated Mar 25 '23 at 08:43

0 Answers0