joncodo
joncodo

Reputation: 2328

regex return array of matches

This is my test string

'Please disregard this.\r\n\r\n**Jonathan O\'Donnell: Estimated Time: 10 Hours.**\r\n\r\n**Jonathan O\'Donnell: 2 Hours May 15, 2015**\r\n**Chris Kuhar: 4 Hours May 30, 2015**'

and this is my Javascript regex so far.

/(\*\*.*?\*\*)/

It matches the first occurrence perfectly but I want all occurrences.

Upvotes: 0

Views: 64

Answers (3)

 /(\*\*.*?\*\*)/g
                ^^

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

If you want, you can storing a more detailed list using .exec, so, you also do a search within each match.

var str = 'Please disregard this.\r\n\r\n**Jonathan O\'Donnell: Estimated Time: 10 Hours.**\r\n\r\n**Jonathan O\'Donnell: 2 Hours May 15, 2015**\r\n**Chris Kuhar: 4 Hours May 30, 2015**';

var reg = /\*\*([^:]+)\:\s*(.+)\*\*/g, fields = [], item;
while(item = reg.exec(str)){
   fields.push({name:item[1], time:item[2]})
}

console.log(fields)
<script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>

Upvotes: 4

borja g&#243;mez
borja g&#243;mez

Reputation: 1051

Use string.match(/your regex/g); ref

Upvotes: 1

Nikhil Batra
Nikhil Batra

Reputation: 3148

You can use /g in your regex expression which will search globally.

The g modifier is used to perform a global match (find all matches rather than stopping after the first match).

So final expression becomes /(\*\*.*?\*\*)/g

Upvotes: 3

Related Questions