Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["@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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading