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

Trying to extract matches from a string matching an expression in JavaScript

I have spent two days on this and I can’t figure it out. Sorry to sound specific. I am trying to match phone numbers in a string and store them in an array. For example:

// An example string
let string = "30000 loaves of bread were purchased by +1777654352"

// I got this from https://ihateregex.io/expr/phone/ and it works for my purpose
const regex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/gmi

// I expect found to have [+1777654352]
const found = string.match(regex);

Instead, I keep getting null in my found array. I am not sure what I am doing wrong. I hope someone out there can point me in the right direction.

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

>Solution :

this regex has ^ on the beginning and $ in the end so I’m pretty sure it matches only on phone numbers that are separated by line breaks, or that are alone in their String.

This regex should work for your needs:

let string = "30000 loaves of bread were purchased by +1777654352"

const regex = /[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}/gmi;

const found = 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