2

I've got the following string, defined in my Javascript code:

var s = "10px solid #101010";

Now, I want to get only the numeric initial part. For this purporse, I tried the following:

s.match(/^([0-9]+)/g);

It works like a charm, and the result was ['10'].

After this test, I also tried to remove the g modifier, as follows:

s.match(/^([0-9]+)/);

I expected the same result, but I was wrong. The result is an array with two solutions: ['10', '10'].

Can someone explain me why? What is the meaning of the last element of the array, in the second case?

Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
  • 1
    Good question, which actually already has a really good answer here: http://stackoverflow.com/questions/18577704/why-capturing-group-results-in-double-matches-regex – Robin May 22 '14 at 13:56
  • ^^ The accepted answer actually does have a very good explanation of this, seems like a duplicate. – adeneo May 22 '14 at 13:59
  • If I have not clear the concept of "capturing group", the answer of question you quote is not adequate (in my opinion)... – Vito Gentile May 22 '14 at 14:03
  • @VitoShadow I guess you actually wanted to put the `+` into the capturing group like `/^([0-9]+)/` otherwise the group would only capture single digits – devnull69 May 22 '14 at 14:10
  • 1
    Also ... the result of removing `g` is `['10', '0']` rather than `['10', '10']` ... at least in my Chrome – devnull69 May 22 '14 at 14:12
  • 1
    just get rid of the brackets ;-) ... `s.match(/^[0-9]+/g);` works like your first example and `s.match(/^[0-9]+/);` doesn't give the duplicate ... you don't even need to specify the start (`^`), as it's the first match `s.match(/[0-9]+/);` ... and if you like, you could use `\d` instead of [0-9] `s.match(/\d+/);` – imma May 22 '14 at 16:21

1 Answers1

-2

'/g' returns all matched ones, It wont stop at first matching point

'g '- Perform a global match (find all matches rather than stopping after the first match)

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Antonio E.
  • 4,381
  • 2
  • 25
  • 35
malkam
  • 2,337
  • 1
  • 14
  • 17