jquery - 正则表达式未按预期工作

标签 jquery regex

编写了一些代码来帮助 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/

相关文章:

javascript - Jquery 转义 "<" ">"

c++ - 忽略包含特殊词的字符串(月)

php - RegEx (.*?) 除了一个字符之外的任何东西

java - 带有正则表达式的 String.replaceAll() 搞砸了

java - 过滤图片的URL路径(img src)获取文件名

javascript - [Wordpress + PHP + MySQL]插件内的数据库SELECT查询没有返回结果

javascript - javascript 函数中未调用 Ajax

jquery - 如何使用jquery改变左边的值

jquery - 使用 JQuery 更改正文背景图像属性

regex - Mongoose :使用正则表达式查询全名