Javascript Regexp循环所有匹配 [英] Javascript Regexp loop all matches

查看:70
本文介绍了Javascript Regexp循环所有匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用堆栈溢出的富文本编辑器做类似的事情。鉴于此文:

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]

我想循环每个 [string]找到[int] 我这样做:

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");
}

这效果很好,它为每个 [string] [int] 提醒'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.

因此在循环中$ 2将代表最初的int部分匹配,我会运行此正则表达式(pseduo)

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
}

这将匹配

[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);

推荐答案

我设法做到了最后用这个:

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);

这篇关于Javascript Regexp循环所有匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆