Javascript Regexp loop all matches

Tom Gullen picture Tom Gullen · Apr 29, 2011 · Viewed 44k times · Source

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:

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

s4y picture s4y · Apr 29, 2011

I agree with Jason that it’d be faster/safer to use an existing Markdown library, but you’re looking for String.prototype.replace (also, use RegExp literals!):

var Text = "[Text Example][1]\n[1][http: //www.example.com]";
var rePattern = /\[(.+?)\]\[([0-9]+)\]/gi;

console.log(Text.replace(rePattern, function(match, text, urlId) {
  // return an appropriately-formatted link
  return `<a href="${urlId}">${text}</a>`;
}));