【发布时间】:2011-08-15 16:17:20
【问题描述】:
我正在尝试使用堆栈溢出的富文本编辑器做类似的事情。鉴于此文本:
[Text Example][1]
[1][http://www.example.com]
我想循环以这种方式找到的每个[string][int]:
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”警报。不过,我需要做的是,对于找到的每个匹配项,将初始匹配项替换为第二个匹配项的组件。
所以在循环中 $2 将代表最初匹配的 int 部分,我会运行这个正则表达式(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]
第一个示例的最终结果是:
<a href="http://www.example.com" rel="nofollow">Text Example</a>
编辑
我现在已经做到了:
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);
【问题讨论】:
标签: javascript regex loops match