Home > Mobile >  Getting substring with regex only returns one value
Getting substring with regex only returns one value

Time:01-14

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?

CodePudding user response:

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));

CodePudding user response:

you can try matchAll on the string

const string = "@trevor you know who @johnny is?"
const regex = /\B@\w /g
console.log([...string.matchAll(regex)])

To get exact values as per shown samples try following, where we are using array values to get the required output.

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

  • Related