如果您需要变量来控制这一点 - 那么您可以尝试
function doReplace(find, repl, str, fullWordsOnly, ignoreSQuotes, ignoreDQuotes, caseSensitive) {
if (caseSensitive == undefined) caseSensitive = false;
var flags = 'gm';
if (!caseSensitive) flags += 'i';
var control = escapeRegExp(find);
if (ignoreDQuotes) control = '(?!\\B"[^"]*)' + control + '(?![^"]*"\\B)';
if (ignoreSQuotes) control = '(?!\\B\'[^\']*)' + control + '(?![^\']*\'\\B)';
if (fullWordsOnly) control = '\\b' + control + '\\b';
return str.replace(new RegExp(control, flags), repl);
}
请注意,当使用诸如 how're 和 can't 之类的缩写词时,单引号可能会出现问题,因此我还提供了一个 hack 来解决这个问题:
// Fix any abbreviated words ('re or 't)
str=str.replace(/'re\/b/gi, ''re');
str=str.replace(/'t\b/gi, ''t');
有关工作演示,请参见http://jsfiddle.net/Abeeee/ct7vayz5/4/