The problem comes from your usage of the .text()
function to get the content of the header. That automatically strips out any markup, returning only the text nodes. What you need to do is get the HTML (use .html()
rather than .text()
) then check for the presence of closing tags at the end of the last word to append back to the new content for your header element:
$('h1').each(function() {
var wordArray = $(this).html().split(' ');
if (wordArray.length > 1) {
wordArray[wordArray.length-2] += ' ' + wordArray[wordArray.length-1];
var lastWord = wordArray.pop();
lastWord = lastWord.replace(/.*((?:<\/\w+>)*)$/, '$1');
$(this).html(wordArray.join(' ') + lastWord);
}
});