1252748
1252748

Reputation: 15372

why does this match return two results when only one exists

Why does this match return two identical matches when only one exists in the string?

/^(.*)$/m


<textarea id="input">one    two three   four    five
1111    2222222 333 444444  555
1111    2222222 333 444444  555
1111    2222222 333 444444  555
    1111    2222222 333 444444  55</textarea>  

var str = $("#input").val();

var arr = str.match(/^(.*)$/m);

console.dir(arr); 
/*
Array[2]
    0: "one two three   four    five"
    1: "one two three   four    five"
    index: 0
    input: "one two three   four    five↵1111   2222222 333 444444  555↵1111    2222222 333 444444  555↵1111    2222222 333 444444  555↵    1111    2222222 333 444444  55"
*/

JSBIN

Upvotes: 1

Views: 90

Answers (1)

Tibos
Tibos

Reputation: 27823

You don't have two matches. The first entry in the array is the entire match, the second is the result of the first capture group (which incidentally is the entire match).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

If the regular expression does not include the g flag, returns the same result as regexp.exec(string).

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

The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

Upvotes: 4

Related Questions