regex - Javascript Regexp loop all matches -


i'm trying similar stack overflow's rich text editor. given text:

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

i want loop each [string][int] found 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, alerts 'ok' each [string][int]. need though, each match found, replace initial match components of second match.

so in loop $2 represent int part matched, , run regexp (pseduo)

while (arrmatch = repattern.exec(text)) {     var findindex = $2; // 1 in our example     new regexp("\\[" + findindex + "\\]\\[(.+?)\\]", "g")      // replace original match hyperlink } 

this match

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

end result first example be:

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

edit

i've gotten far 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);

i agree jason it’d faster/safer use existing markdown library, you’re looking 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 appropriately-formatted link    return `<a href="${urlid}">${text}</a>`;  }));


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -