如何在javascript中的替换内循环正则表达式的匹配? [英] How do I loop through a regex's matches inside a replace in javascript?
本文介绍了如何在javascript中的替换内循环正则表达式的匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JavaScript(< P>
中的空格是非破坏的):
I have the following JavaScript (the spaces in the <P>
s are non-breaking):
var html = '...<li>sub 2</li></ol></li></ol>\n\
<p> i. subsub 1</p>\n\
<p> ii. subsub 2</p>\n\
<ol start="2"> \n\
<ol start="3"> \n\
<li>sub 3</li></ol>...';
$(function () {
var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:<ol(?:\sstyle=\"[^\"]+\")?\sstart=\"[^\"]+\">\s*)+/i;
html = html.replace(nestedListFixer, function($0, $1){
var lis = ""
$.each($1, function () {
lis += "<li>" + this + "</li>\n";
});
alert("<ol>\n" + lis + "</ol></li>");
return "<ol>\n" + lis + "</ol></li>";
});
});
alert()
的输出:
<ol>
<li>s</li>
<li>u</li>
<li>b</li>
<li>s</li>
<li>u</li>
<li>b</li>
<li> </li>
<li>2</li>
</ol></li>
以下是我希望的结果:
<ol>
<li>subsub 1</li>
<li>subsub 2</li>
</ol></li>
如何在 $ 1 $ c中正确循环每个匹配$ c>?
更新:简化模式和匹配示例:
Update: simplified pattern and matching example:
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
推荐答案
以下是我提出的解决方案,但效率似乎不高:
Here's the solution that I came up with but it doesn't seem to be very efficient:
$(function () {
var nestedListFixer = /(?:<\/li><\/ol>\s*)+(?:<p>(?:&(?:nbsp|\#0*160|x0*A0);)+(?:\s[ivxlcdm]+\.)(?:&(?:nbsp|\#0*160|x0*A0);)+\s(.*?)<\/p>\s*)+(?:<ol(?:\sstyle=\"[^\"]+\")?\sstart=\"[^\"]+\">\s*)+/gi;
var nestedListItem = /<p>(?:&(?: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 += "<li>" + this.replace(nestedListItem, "$1") + "</li>\n";
});
return "<ol>\n" + lis + "</ol></li>";
});
});
...或上面的简单示例:
...or for the simpler example above:
$(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()
函数内部不会看起来很经济。它确实给了我正在寻找的输出。
Doing a .replace()
substitution, inside a loop of a .match()
array, inside of a custom .replace()
function just doesn't seem like it is very economical. It does give me the output that I was looking for though.
这篇关于如何在javascript中的替换内循环正则表达式的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文