I have function to bold part of line before colon.
//Fast regex (time: 0)
var colonRegex = /^[^*:\n]+:/gm;
and
//Slow regex (time: 139) Limit by 10 words
//var colonRegex = /^([^*:\n ]+ ?){1,10}:/gm;
// I have issue with it when I want to apply replace to tens of divs (it freezes chrome)
var bolded = str.replace(colonRegex, function(match) {
return "<b>"+match+"</b>";
});
you can test it on jsfiddle: http://jsfiddle.net/damg7zuk/4/
Where I do a mistake? I can make word limitation inside the callback. Can it be done better in regex itself? Thank you for your trick.
Your /^([^*:\n ]+ ?){1,10}:/gm
regex exhibits catastrophic backtracking: You're nesting the +
and the {1,10}
repetition with (possibly) nothing in between. Fix this by making the blank that separates the groups compulsory to match:
/^([^*:\n ]+ ){0,9}[^*:\n ]+:/gm
# ^
or
/^[^*:\n ]+( [^*:\n ]+){0,9}:/gm
js level can be so:
var bolded = str.replace(colonRegex, function(match) {
if (match.indexOf(".") > 0){
match1 = match.slice(0,(match.indexOf(".")+1));
match2 = match.slice(match.indexOf(".")+1);
match = match1+"<b>"+match2+"</b>";
return match;
}
return "<b>"+match+"</b>";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With