gpt4 book ai didi

JavaScript 正则表达式性能。

转载 作者:搜寻专家 更新时间:2023-11-01 04:11:26 24 4
gpt4 key购买 nike

我有一个函数可以纠正一列不常见的大写单词的大写:

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 个这样的词。显然,现在我正在执行几十个(可能是数百个;该数组有一种随着时间的推移而增长的不可思议的趋势)实际上什么都不做的函数调用。

我怎样才能使这段代码更快并摆脱不必要的函数调用?

示例输入:

My iphone 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.

最佳答案

您可以构建包含所有单词的正则表达式,通过将每个单词括在括号中来捕获每个单词。在替换中使用它会提供足够的信息来恢复替换函数中的原始单词。

  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.

This turns out to be faster then the original code .

关于JavaScript 正则表达式性能。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5324757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com