var $element = $('p');
var string = 'foo';
var count = $element.text().match(string, 'g').length;
if(count) {
var rand = Math.floor((Math.random() * count) + 1);
$element.text(function(i, text) {
var matchNumber = 0;
return text.replace(new RegExp(string, 'g'), function(text) {
matchNumber++;
if(matchNumber == rand) {
return 'buz';
}
return text;
});
});
}
Explanation:
First of all we have to know the range to the random. We can get it matching the string and then get the length.
Then you have to match it again and increase a counter which will be used to know which match is the currently one.
If the current match is equal to the random number we have to replace the text.
demo