如何从字符串中删除所有Wiki模板
How to remove all Wiki templates from a string?
我有维基百科文章的内容,内容如下:
{{Use mdy dates|date=June 2014}}
{{Infobox person
| name = Richard Matthew Stallman
| image = Richard Stallman - Fête de l'Humanité 2014 - 010.jpg
| caption = Richard Stallman, 2014
| birth_date = {{Birth date and age|1953|03|16}}
| birth_place = New York City
| nationality = American
| other_names = RMS, rms
| known_for = Free software movement, GNU, Emacs, GNU Compiler Collection|GCC
| alma_mater = Harvard University,<br />Massachusetts Institute of Technology
| occupation = President of the Free Software Foundation
| website = {{URL|https://www.stallman.org/}}
| awards = MacArthur Fellowship<br />EFF Pioneer Award<br />''... see #Honors and awards|Honors and awards''
}}
或
{{Citation needed|date=May 2011}}
如何移除?我可以使用这个正则表达式:/'{'{[^}]+'}'}/g
,但它不适用于像Infobox 这样的嵌套模板
我试着用这段代码先删除嵌套模板,然后再删除Infobox,但我得到了错误的结果。
var input = document.getElementById('input');
input.innerHTML = input.innerHTML.replace(/'{'{[^}]+'}'}/g, '');
<pre id="input"> {{Use mdy dates|date=June 2014}}
{{Infobox person
| name = Richard Matthew Stallman
| image =Richard Stallman - Fête de l'Humanité 2014 - 010.jpg
| caption = Richard Stallman, 2014
| birth_date = {{Birth date and age|1953|03|16}}
| birth_place = New York City
| nationality = American
| other_names = RMS, rms
| known_for = Free software movement, GNU, Emacs, GNU Compiler Collection|GCC
| alma_mater = Harvard University,<br />Massachusetts Institute of Technology
| occupation = President of the Free Software Foundation
| website = {{URL|https://www.stallman.org/}}
| awards = MacArthur Fellowship<br />EFF Pioneer Award<br />''... see #Honors and awards|Honors and awards''
}}</pre>
Javascript正则表达式没有匹配嵌套方括号的功能(如递归或平衡组)。regex的一种方法是用一种模式多次处理字符串,该模式可以找到最里面的方括号,直到没有什么可替换:
do {
var cnt=0;
txt = txt.replace(/{{[^{}]*(?:{(?!{)[^{}]*|}(?!})[^{}]*)*}}/g, function (_) {
cnt++; return '';
});
} while (cnt);
图案细节:
{{
[^{}]* # all that is not a bracket
(?: # this group is only useful if you need to allow single brackets
{(?!{)[^{}]* # an opening bracket not followed by an other opening bracket
| # OR
}(?!})[^{}]* # same thing for closing brackets
)*
}}
如果不想多次处理字符串,也可以在找到方括号时逐个字符地读取字符串,增加和减少标志。
使用split和Array.prototype.reduce
:的另一种方法
var stk = 0;
var result = txt.split(/({{|}})/).reduce(function(c, v) {
if (v == '{{') { stk++; return c; }
if (v == '}}') { stk = stk ? stk-1 : 0; return c; }
return stk ? c : c + v;
});
相关文章:
- 强制模板刷新ember.js
- Dojo不解析自定义小部件的模板html中的小部件声明性
- 如何将JSON数据导入我的ejs模板
- 我的模板未被解析
- 主干模板:index.jst.eco到index.jst.ejs
- 在underscorejs模板中使用闭包
- angularjs+rails应用程序中未显示模板
- 以可优化的方式使用requirejs加载模板
- Jquery模板,如果xx&&如果yy
- 从ng模板访问作用域
- 我的django模板布尔变量是't在javascript中按预期工作
- 访问jsrender模板中的全局javascript变量并更新它
- 聚合物0.5.5:核心列表中的条件模板和/或模板动态参考
- 如何在速度模板中获取LiferayPortlet实例id
- 基于localStorage的Meteor激活模板
- 指令的模板必须只有一个根元素:With restrict E&替换true
- 如何在使用组件时定义模板url
- 如何将javascript变量传递到Meteor Spacebars模板中
- 如何从字符串中删除所有Wiki模板
- 延迟回调中出现异常:错误:没有这样的模板:wiki