Getting substring with regex only returns one value

I am trying to get all substrings of "username" from a string. A username must start with an @ and end with a " ". Here is how I am doing this:

const string = "@trevor you know who @johnny is?"
const regex = /\B@\w+/
console.log(regex.exec(string))

Output:

["@trevor"]

Expected output:

["@trevor", "@johnny"]

How can I make the regex remove multiple matches from the string rather than just the first?

>Solution :

If we use match() with your regex in global mode your code is working:

const string = "@trevor you know who @johnny is?"
const regex = /\B@\w+/g
console.log(string.match(regex));

Leave a Reply