2

I have this regex expression

let paragraph = "112-39-8552 asdasdas 123-58-3695";
let result = paragraph.match(/(\d{3}\-\d{2}-\d{4})+/);
console.log(result);

I will have this as a result

[
  '112-39-8552',
  '112-39-8552',
  index: 0,
  input: '112-39-8552 asdasdas 123-58-3695',
  groups: undefined
]

It only find the first pattern but not the second

how can I include 123-58-3695 in the search result?

2 Answers 2

2

Use the g flag. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global

let result = paragraph.match(/(\d{3}\-\d{2}-\d{4})+/g);

The value of global is a Boolean and true if the "g" flag was used; otherwise, false. The "g" flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ("g") and sticky ("y") will ignore the global flag and perform sticky matches.

Sign up to request clarification or add additional context in comments.

Comments

1

You just need to pass the "g" flag to the regex like:

let paragraph = "112-39-8552 asdasdas 123-58-3695";
let result = paragraph.match(/(\d{3}\-\d{2}-\d{4})+/g);
console.log(result);

The g is for global search. Meaning it'll match all occurrences. Without the g flag, it'll only test for the first match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.