Javascript Regexp loop all matches
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>`;}));
I managed to do it in the end with this:
var Text = "[Text Example][1]\n[1][http: //www.example.com]";// Find resource linksreg = 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);
Here we're using exec method, it helps to get all matches (with help while loop) and get position of matched string.
var input = "A 3 numbers in 333"; var regExp = /\b(\d+)\b/g, match; while (match = regExp.exec(input)) console.log("Found", match[1], "at", match.index); // → Found 3 at 2 // Found 333 at 15