var totalNToReplace = 3; jQuery().ready(function(e) { jQuery('p').replaceFirstNWith(/\bahmad\b/i, "ahmad", '1'); }); // Following function slightly modified from: https://codereview.stackexchange.com/questions/14010/replacing-the-first-n-occurrences-of-a-term jQuery.fn.replaceFirstNWith = function(yourregex, replacetext, firstNToReplace) { var regexp, flags = "g"; // Allow user to pass a RegExp object instead of a string. if( yourregex instanceof RegExp ) { // No way to set the global flag on an existing regexp object, // so "copy" it by checking flags, and extracting the source if( yourregex.ignoreCase ) flags += "i"; if( yourregex.multiline ) flags += "m"; yourregex = yourregex.source; } regexp = new RegExp(yourregex, flags); // build the regexp jQuery(this).each(function (index, value) { if( firstNToReplace < 0 ) return; // skip if enough replacements have been made already if( totalNToReplace < 0 ) return; // skip if enough total replacements have been made already var html = jQuery(this).html().replace(regexp, function () { if( --firstNToReplace < 0 || --totalNToReplace < 0 ) { // decrement count and check return arguments[0]; // return the matched string with no changes } return replacetext; }); jQuery(this).html(html); }); }