mplungjan
mplungjan

Reputation: 177786

regular expression not working as expected

Wrote some code to help with Find special markers in sequence and do something to the text in between

Here is the fiddle: http://jsfiddle.net/mplungjan/GyPHH/

Why does it only run once per regex and how would you handle the nested entries

<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);
  });
});

Upvotes: 1

Views: 263

Answers (2)

Guffa
Guffa

Reputation: 700262

That's because you are replacing the first value found over and over. If you examine the result you should find that you have wrapped the first match with multiple tags.

You are doing a double loop where you first locate the matches, then replace each match. You can just replace them straight away. Also, you are getting the html out and putting it back for each iteration, when you can just do it once:

var res = {
    boldIt:/\*\*(.*?)\*\*/g,
    underlineIt:/\_\_(.*?)\_\_/g
}
var s = $("#texts").html();    
$.each(res, function(type, re) {
  s = s.replace(re,'<span class="'+type+'" >$1</span>');
});
$("#texts").html(s);

Upvotes: 2

JJJ
JJJ

Reputation: 33163

That code is needlessly complicated. Try this:

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>' ) );
});

Upvotes: 3

Related Questions