You can use jQuery's .each()
to iterate through the h1
s.
$('h1').each(function(){
var words = $(this).text().split(' ');
var randomWord = words[Math.floor(Math.random()*words.length)];
$(this).html(
$(this).html().replace(new RegExp( randomWord, 'g'),'<i>'+randomWord+'</i>')
);
});
Demo: http://jsfiddle.net/RT25S/1/
Edit: I just noticed a bug in my answer that is also in your question and probably in the other answers.
In titles like this is another one
, is
is italicised in both is
and this
. scrowler commented that when the selected word is in the title multiple times all of them will be italicised, but I doubt you intended for partial words to be italicised.
The fixes are relatively simple. Just check for spaces before and after the word. You also have to allow for words at the beginning and end of the title using the ^
and $
metacharacters.
Ideally we could use \b
, which is a "word boundary", instead but it doesn't seem to work when words end with non-alphanum characters.
You should also probably escape the randomly-selected word before including it in a regex in case it contains any special characters. I added the escaping regex from Is there a RegExp.escape function in Javascript?.
The updated code:
$('h1').each(function(){
var words = $(this).text().split(' ');
var randomWord = words[Math.floor(Math.random()*words.length)];
// Escape the word before including it in a regex in case it has any special chars
var randomWordEscaped = randomWord.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
$(this).html(
$(this).html().replace(
//new RegExp( '\\b' + randomWordEscaped + '\\b', 'g' ),
new RegExp( '(^| )' + randomWordEscaped + '( |$)', 'g' ),
'<i> ' + randomWord + ' </i>'
)
);
});
And the updated JSFiddle: http://jsfiddle.net/RT25S/3/
Note that I added spaces after and before the <i>
tags because the regex now captures them. (This still works for words at the beginning/ends of titles because HTML ignores that whitespace.)