简体   繁体   English

搜索最高性能的字符串替换为javascript的方法

[英]Searching for most performant way for string replacing with javascript

I'm programming my own autocomplete textbox control using C# and javascript on clientside. 我在客户端使用C#和javascript编写自己的自动完成文本框控件。 On client side i want to replace the characters in string which matching the characters the user was searching for to highlight it. 在客户端,我想替换字符串中与用户要突出显示的字符匹配的字符。 For example if the user was searching for the characters 'bue' i want to replace this letters in the word 'marbuel' like so: 例如,如果用户正在搜索字符“ bue”,我想将单词“ marbuel”中的这些字母替换为:

mar<span style="color:#81BEF7;font-weight:bold">bue</span>l

in order to give the matching part another color. 为了给匹配部分提供另一种颜色 This works pretty fine if i have 100-200 items in my autocomplete, but when it comes to 500 or more, it takes too mutch time. 如果我的自动完成中包含100-200个项目,则此方法效果很好,但是当涉及500个或更多项目时,则花费了很多时间。

The following code shows my method which does the logic for this: 以下代码显示了执行此操作逻辑的方法:

 HighlightTextPart: function (text, part) {
    var currentPartIndex = 0;
    var partLength = part.length;
    var finalString = '';
    var highlightPart = '';
    var bFoundPart = false;
    var bFoundPartHandled = false;
    var charToAdd;
    for (var i = 0; i < text.length; i++) {
        var myChar = text[i];
        charToAdd = null;
        if (!bFoundPart) {
            var myCharLower = myChar.toLowerCase();
            var charToCompare = part[currentPartIndex].toLowerCase();
            if (charToCompare == myCharLower) {
                highlightPart += myChar;
                if (currentPartIndex == partLength - 1)
                    bFoundPart = true;

                currentPartIndex++;
            }
            else {
                currentPartIndex = 0;
                highlightPart = '';
                charToAdd = myChar;
            }
        }
        else
            charToAdd = myChar;

        if (bFoundPart && !bFoundPartHandled) {
            finalString += '<span style="color:#81BEF7;font-weight:bold">' + highlightPart + '</span>';
            bFoundPartHandled = true;
        }

        if (charToAdd != null)
            finalString += charToAdd;
    }
    return finalString;
},

This method only highlight the first occurence of the matching part. 此方法仅突出显示匹配部分的首次出现。 I use it as follows. 我使用它如下。 Once the request is coming back from server i build an html UL list with the matching items by looping over each item and in each loop i call this method in order to highlight the matching part. 一旦请求从服务器返回,我就通过遍历每个项目构建带有匹配项的html UL列表,并在每个循环中调用此方法以突出显示匹配的部分。

As i told for up to 100 items it woks pretty nice but it is too mutch for 500 or more. 正如我对最多100件商品所讲的那样,它的炒锅还不错,但是对于500或更多的东西来说太辣了。

Is there any way to make it faster? 有什么方法可以使其更快? Maybe by using regex or some other technique? 也许通过使用正则表达式或其他技术?

I also thought about using "setTimeOut" to do it in a extra function or maybe do it only for the items, which currently are visible, because only a couple of items are visible while for the others you have to scroll. 我还考虑过使用“ setTimeOut”在一个额外的功能中执行此操作,或者可能仅对当前可见的项目执行此操作,因为只有几个项目可见,而对于其他项目则必须滚动。

Try limiting visible list size, so you are only showing 100 items at maximum for example. 尝试限制可见列表的大小,例如,您最多只能显示100个项目。 From a usability standpoint, perhaps even go down to only 20 items, so it would be even faster than that. 从可用性的角度来看,甚至可能只减少到20个项目,因此它甚至会更快。 Also consider using classes - see if it improves performance. 还可以考虑使用类-看看它是否可以提高性能。 So instead of 所以代替

mar<span style="color:#81BEF7;font-weight:bold">bue</span>l

You will have this: 您将拥有:

mar<span class="highlight">bue</span>l

String replacement in JavaScript is pretty easy with String.replace() : 使用String.replace()在JavaScript中替换字符串非常容易:

function linkify(s, part)
{
    return s.replace(part, function(m) {
        return '<span style="color:#81BEF7;font-weight:bold">' + htmlspecialchars(m) + '</span>';
    });
}

function htmlspecialchars(txt)
{
    return txt.replace('<', '&lt;')
        .replace('>', '&gt;')
        .replace('"', '&quot;')
        .replace('&', '&amp;');
}

console.log(linkify('marbuel', 'bue'));

I fixed this problem by using regex instead of my method posted previous. 我通过使用正则表达式而不是之前发布的方法解决了此问题。 I replace the string now with the following code: 我现在用以下代码替换字符串:

return text.replace(new RegExp('(' + part + ')', 'gi'), "<span>$1</span>");

This is pretty fast. 这非常快。 Much faster as the code above. 与上面的代码相比快得多。 500 items in the autocomplete seems to be no problem. 自动完成中的500个项目似乎没有问题。 But can anybody explain, why this is so mutch faster as my method or doing it with string.replace without regex? 但是任何人都可以解释一下,为什么这比我的方法更快,或者使用不带正则表达式的string.replace来完成呢? I have no idea. 我不知道。

Thx! 谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 深度复制对象的最有效方式javascript - most performant way to deep copy objects javascript 编写自定义.on()/。bind()JavaScript的最佳方式 - Most performant way to write custom .on()/.bind() JavaScript 用分隔符连接字符串的最有效方法是什么 - What is the most performant way to concatenate a string with a separator 在JavaScript中检查字符串是否为空(即仅包含空格)的最高性能方法? - The most performant way to check if a string is blank (i.e. only contains whitespace) in JavaScript? 在 JavaScript 中,确定字符串中第一个字符的最高效方法是什么:startsWith、charAt 或 [0] - In JavaScript, what's the most performant way to determine the first character in a string: startsWith, charAt, or [0] JavaScript:最高效、最高效的 ArrayBuffer 内存分区方式 - JavaScript: Most efficient and performant way to partition ArrayBuffer memory 调用javaScript物理引擎的更新循环的最佳方式 - Most performant way to call update loop of a javaScript physics engine Javascript:对象数组到包含值数组的对象-最有效的方式? - Javascript: Array of objects to object containing arrays of values - most performant way? 使用生成的ID创建JavaScript集合的最高效方法 - Most performant way to create a JavaScript collection with generated IDs javascript / jQuery - 在不替换整个正文的情况下替换正文中所有字符串的最有效方法是什么 - javascript / jQuery - What is the most efficiënt way to replace all the occurrences of a string in a body without replacing the entire body
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM