Reputation: 3648
Im trying to replace the second and third word in an html element.
so far I can replace the second word using this:
jQuery("article#box-1 h2.join-box-head").each(function(i, v){
newHTML = jQuery(this).html()
.replace(/\s(.*?)\s/,'<span class="error">$1 </span>')
jQuery(this).html(newHTML);
});
but im having a hard time selecting the third word too
HTML
<article id="box-1">
<h2 class="join-box-head">JOIN WITH YOUR FAMILY</h2>
</article>
any ideas?
Upvotes: 1
Views: 527
Reputation: 13812
Is regex really needed?
jQuery("article#box-1 h2.join-box-head").each(function(i, v){
var newHTML = jQuery(this).html().split(" ");
for (var i = 1; i < 3; i++)
newHTML[i] = '<span class="error">' + newHTML[i] + '</span>';
jQuery(this).html(newHTML.join(" "));
});
Or both in one span
jQuery("article#box-1 h2.join-box-head").each(function(i, v){
var newHTML = jQuery(this).html().split(" ");
newHTML[1] = '<span class="error">' + newHTML[1];
newHTML[2] = newHTML[2] + '</span>';
jQuery(this).html(newHTML.join(" "));
});
Upvotes: 2
Reputation: 8219
A solution that is not efficient but fast would be to call the funcion you provided twice, because when you replace the second word, the third word becomes the second word. So, call the same function twice if you do not want to make any code changes and you do not care about performance efficiency.
Upvotes: 0