如何在javascript中的替换内循环正则表达式的匹配?
我有以下JavaScript( 的空格是非破坏的):
var html = '...sub 2 \n\ i. subsub 1
\n\ ii. subsub 2
\n\ \n\ \n\ - sub 3
...'; $(function () { var nestedListFixer = /(?:\s*)+(?:(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)\s*)+(?:
\s*)+/i; html = html.replace(nestedListFixer, function($0, $1){ var lis = "" $.each($1, function () { lis += "- " + this + "
\n"; }); alert("\n" + lis + "
"); return "\n" + lis + "
"; }); });
alert()
的输出:
- s
- u
- b
- s
- u
- b
-
- 2
这是我希望它会是:
- subsub 1
- subsub 2
如何在$1
正确循环每个匹配?
更新:简化模式和匹配示例:
var text = '1ab2cb3cd4ab5cb6cd7'; $(function () { var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/i; text = text.replace(textFixer, function($0, $1){ var numbers = ""; $.each($1, function () { numbers += this; }); alert(numbers); return numbers; }); alert(text); }); // actual text: // 13467 // desired text: // 1234567
您提供的更新示例仅匹配“3”而非“13467”,如您所述。 如果你改变你的正则表达式进行全局匹配,它将返回“36”而仍然不是“13467”。
你的第一个例子也没有输出任何东西。
你只是试图获得正则表达式的匹配并循环匹配?
如果是这样,
var text = '1ab2cb3cd4ab5cb6cd7'; var matches = text.match(/(\d)/g); for (i=0; i
这是我提出的解决方案,但它看起来效率不高:
$(function () { var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:
\s*)+/gi; var nestedListItem = /(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*/gi; // fix nested lists html = html.replace(nestedListFixer, function($0, $1){ var lis = "" $.each($0.match(nestedListItem), function () { lis += "
- " + this.replace(nestedListItem, "$1") + "
\n"; }); return "\n" + lis + "
"; }); });
……或者对于上面简单的例子:
$(function () { var textFixer = /(?:a)(?:b(.*?)c)+(?:d)/gi; var textItem = /b(.*?)c/gi; text = text.replace(textFixer, function($0, $1){ var numbers = ""; $.each($0.match(textItem), function () { numbers += this.replace(textItem, "$1"); }); return numbers; }); });
在自定义.replace()
函数内部的.match()
数组循环内进行.replace()
替换似乎不太经济。 它确实给了我正在寻找的输出。
一个漂亮的循环可以使用钩子模式:
var text = '1ab2cb3cd4ab5cb6cd7'; text.match(/(\d)/g).forEach(function(element,index){ console.log(element) });