charmeleon charmeleon - 1 year ago 41
Javascript Question

Validate whole string and get all matches

I'd like to validate my string input if it it contains digits separated by spaces. I tried using the regex


and was able to check the validity via the
method, but when I use
it does not give me the correct matches.

For example, I have input

2 3 4 5

When I try to use the
method, I get

["", "2", "5", ""]

I was expecting the result to be

["2", "3", "4", "5"]

Any suggestion is greatly appreciated, thanks!

Answer Source

Your ^(\d)(?:\s(\d))*$ regex splits the string correctly as ["", "2", "5", ""] because:

  • The first (\d) captures a digit at the beginning of the string, and inserts it into the resulting array. Since the digit is found at the beginning, the empty string before the string start and the first digit appears as the first array element, and 2 is the second
  • The (?:\s(\d))* construct is a *-quantified non-capturing group that matches 0+ sequenes of a whitespace followed with a digit, and the digit is captured. That is, each time a space+digit is matched, the Group 2 slot is re-written with a new value, and the last one is kept that way, which is 5. Since the right-hand split border happened at the end of the string, the empty string is added to the resulting array.

If your string is already validated, you need no /\d+/g, you may just split with a space (note that capturing groups are redundant in your regex then):

var s = "2 3 4 5";
if (/^\d(?:\s\d)*$/.test(s)) {
  console.log(s.split(" "));  
// var s = "2 3 4 a"; won't show any output