编写了一些代码来帮助 Find special markers in sequence and do something to the text in between
这是 fiddle :http://jsfiddle.net/mplungjan/GyPHH/
为什么每个正则表达式只运行一次以及如何处理嵌套条目
<div id="texts">
**this** **would** make it **bold** __this would__ make it __underlined__
__**how about bold and underlined**__
and
**__the other way around__**
</div>
var res = {
boldIt:/\*\*(.*?)\*\*/g,
underlineIt:/\_\_(.*?)\_\_/g
}
$.each(res, function(type, re) {
var s = $("#texts").html();
var m = re.exec(s);
var found = m[0];
$.each(m, function(index, value) {
if (index==0) return true;
var html = s.replace(found,'<span class="'+type+'" >'+value+'</span>',"g");
$("#texts").html(html);
});
});
最佳答案
该代码不必要地复杂。试试这个:
var res = {
boldIt:/\*\*(.*?)\*\*/g,
underlineIt:/\_\_(.*?)\_\_/g
}
$.each(res, function(type, re) {
var txt = $( "#texts" ).html();
$( "#texts" ).html( txt.replace( re, '<span class="'+type+'" >$1</span>' ) );
});
关于jquery - 正则表达式未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996133/