您可以构建包含所有单词的正则表达式,通过将每个单词括在括号中来捕获它。在替换中使用它将提供足够的信息来恢复替换函数中的原始单词。
function correct (text, words) {
return text.replace (RegExp ('\\b(?:(' + words.join (')|(') + '))\\b', 'ig'), function (m) {
for (var a = arguments.length - 2; a--;)
if (arguments[a])
return words[a-1] || m;
});
}
console.log (correct ("My iphone itunes divx firewire application has a user form under uiviewcontroller. When I start application again some of my uiview changes its positions and sizes. (These uiviews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the uiview changes can be done.",
["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand",
"iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook",
"MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
// ...
"UIViewController","UIView",
"Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"]));
My iPhone iTunes DivX FireWire application has a user form under UIViewController. When I start application again some of my UIView changes its positions and sizes. (These UIViews depend on keyboard position) Somewhere is definitely my fault. I try to figure what is going on when application starts again from background and where the UIView changes can be done.
事实证明这比原始代码更快 http://jsperf.com/regex-matching.