我正在尝试使用 Stack Overflow 的富文本编辑器进行类似操作。 给定此文本:
[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");
}
因此,在循环中,$2将表示最初匹配的int部分,并且我将运行此正则表达式(伪代码)。
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);