Tom Gullen Tom Gullen - 3 months ago 8
Javascript Question

Javascript Regexp loop all matches

I'm trying to do something similar with stack overflow's rich text editor. Given this text:

[Text Example][1]

[1][http://www.example.com]


I want to loop each
[string][int]
that is found which I do this way:



var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
var arrMatch = null;
var rePattern = new RegExp(
"\\[(.+?)\\]\\[([0-9]+)\\]",
"gi"
);
while (arrMatch = rePattern.exec(Text)) {
console.log("ok");
}





This works great, it alerts 'ok' for each
[string][int]
. What I need to do though, is for each match found, replace the initial match with components of the second match.

So in the loop $2 would represent the int part originally matched, and I would run this regexp (pseduo)

while (arrMatch = rePattern.exec(Text)) {
var FindIndex = $2; // This would be 1 in our example
new RegExp("\\[" + FindIndex + "\\]\\[(.+?)\\]", "g")

// Replace original match now with hyperlink
}


This would match

[1][http://www.example.com]


End result for first example would be:

<a href="http://www.example.com" rel="nofollow">Text Example</a>


Edit



I've gotten as far as this now:



var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
reg = new RegExp(
"\\[(.+?)\\]\\[([0-9]+)\\]",
"gi");
var result;
while ((result = reg.exec(Text)) !== null) {
var LinkText = result[1];
var Match = result[0];
Text = Text.replace(new RegExp(Match, "g"), '<a href="#">" + LinkText + "</a>');
}
console.log(Text);




Answer

I managed to do it in the end with this:

var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
reg = new RegExp(
  "\\[(.+?)\\]\\[([0-9]+)\\]",
  "gi");
var result;
while (result = reg.exec(Text)) {
  var LinkText = result[1];
  var Match = result[0];
  var LinkID = result[2];
  var FoundURL = new RegExp("\\[" + LinkID + "\\]\\[(.+?)\\]", "g").exec(Text);
  Text = Text.replace(Match, '<a href="' + FoundURL[1] + '" rel="nofollow">' + LinkText + '</a>');
}
console.log(Text);