function nthReplace(str, regex, newValue, n) { return str.replace(regex, function(a) { return (--n == 0) ? newValue : a; }); } alert(nthReplace("content 1 content 2 content 3", /content/g, "****", 2));