0

My string is defined as;

var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var res = str.match(/\[\[(.*[^\]])\]\]/g)

I would like to extract "http://www.yahoo.com" and "more" but I am getting

[ '[[http://www.yahoo.com]] again [[more]]' ]

What should the regex be?

P Hemans
  • 3,762
  • 10
  • 42
  • 70

3 Answers3

2

Putting ]] inside a negated character class won't give the result you want. Use inside a negative lookahead like below.

\[\[((?:(?!\]\]).)*)\]\]

DEMO

> var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
undefined
> var re = /\[\[((?:(?!\]\]).)*)\]\]/g;
undefined
> var matches = [];
undefined
> while (m = re.exec(str)) {
..... matches.push(m[1]);
..... }
2
> console.log(matches)
[ 'http://www.yahoo.com', 'more' ]
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
2

Use the exec() method in a loop, pushing the match result of the captured group to the results array. Also, remove the dot . greedy operator * from your capturing group because it is not necessary since you use negation.

var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var re  = /\[\[([^\]]*)]]/g, 
matches = [];

while (m = re.exec(str)) {
  matches.push(m[1]);
}
console.log(matches) //=> [ 'http://www.yahoo.com', 'more' ]
hwnd
  • 65,661
  • 4
  • 77
  • 114
0
var str = 'participant Tracking [[http://www.yahoo.com]] again [[more]]'
var res = str.match(/\[\[(.+?)\]\]/)
console.log(res[1]);
Duniyadnd
  • 3,854
  • 1
  • 19
  • 26
  • This satisfies the test case. I'd be inclined to upvote if it was more than a "try this" answer. – Gary Oct 10 '14 at 02:04
  • You're right, I misread the question for some reason. I'll leave it as is, there are sufficient responses here. – Duniyadnd Oct 10 '14 at 02:24