我有一个函数可以纠正大写异常大写单词的大写:
var line = "some long string of text";
["AppleScript", "Bluetooth", "DivX", "FireWire", "GarageBand",
"iPhone", "iTunes", "iWeb", "iWork", "JavaScript", "jQuery", "MacBook",
"MySQL", "PowerBook", "PowerPoint", "QuickTime", "TextEdit", "TextMate",
// ...
"Wi-Fi", "Xcode", "Xserve", "XMLHttpRequest"].forEach(function(name) {
line = line.replace(RegExp(name, "gi"), name);
});
现在我遇到的问题是大多数输入字符串平均包含0到3个字。显然现在我正在做几十个(可能有几百个;那个数组有一种不可思议的趋势,随着时间的推移而增长)函数调用基本上什么都不做。
如何更快地编写代码并摆脱不必要的函数调用?
示例输入:
我的iphone应用程序在UIViewController下有一个用户表单。当我再次启动应用程序时,我的一些UIView会更改其位置和大小。 (这些UIViews依赖于键盘位置)某处绝对是我的错。我试图弄清楚当应用程序从后台再次启动时会发生什么,并且可以完成UIView更改。
答案 0 :(得分:5)
您可以构建包含所有单词的正则表达式,通过将每个单词括在括号中来捕获每个单词。在替换中使用它将提供足够的信息来恢复替换函数中的原始单词。
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.