Tom*_*len 37 javascript regex loops match
我正在尝试使用堆栈溢出的富文本编辑器做类似的事情.鉴于此文本:
[Text Example][1]
[1][http://www.example.com]
Run Code Online (Sandbox Code Playgroud)
我想循环[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");
}
Run Code Online (Sandbox Code Playgroud)
这很好用,每个都警告'确定' [string][int]
.我需要做的是,对于找到的每个匹配,用第二个匹配的组件替换初始匹配.
所以在循环中$ 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
}
Run Code Online (Sandbox Code Playgroud)
这会匹配
[1][http://www.example.com]
Run Code Online (Sandbox Code Playgroud)
第一个例子的最终结果是:
<a href="http://www.example.com" rel="nofollow">Text Example</a>
Run Code Online (Sandbox Code Playgroud)
我现在已经达到了这个目的:
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);
Run Code Online (Sandbox Code Playgroud)
s4y*_*s4y 37
我同意杰森认为使用现有的Markdown库更快/更安全,但你正在寻找String.prototype.replace(同样,使用RegExp文字!):
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>`;
}));
Run Code Online (Sandbox Code Playgroud)
Tom*_*len 33
我最终设法做到了这一点:
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);
Run Code Online (Sandbox Code Playgroud)
在这里,我们使用 exec方法,它有助于获取所有匹配项(借助while循环帮助)并获取匹配字符串的位置。
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
Run Code Online (Sandbox Code Playgroud)