Search code examples
javascriptjqueryregexstringhighlighting

JS Highlighting Of Text Strings


Using a small plugin to highlight text strings from an input field within a form.

JavaScript text higlighting jQuery plugin

I have modified the code slightly to allow the user to add multiple strimgs into the input field by splitting them with a comma which will highlight multiple keywords.

This works great in this instance: stack,overflow,js

However if I was to type in stack,overflow,js, (note the , after the last string) it hangs the browser and becomes unresponsive.

The code I am using is:

$(function() { 
    if ( $("input#searchterm").val().length > 0 ) {
        $("input#searchterm").addClass('marked-purple');
        var arrayOfKeyWords= $("input#searchterm").val().split(',');
        for (var i=0;i<arrayOfKeyWords.length;i++) {
            $('.message p.messagecontent').highlight(arrayOfKeyWords[i]);
        }
    }           
});

Does anyone have an idea of how to ignore the last comma if the user has added it?

Thanks in advance


Solution

  • You could do an empty value check before calling highlight(), like this:

    if ($("#searchterm").val().length > 0) {
        $("#searchterm").addClass('marked-purple');
        var arrayOfKeyWords = $("#searchterm").val().split(',');
        for (var i = 0; i < arrayOfKeyWords.length; i++) {
            if (arrayOfKeyWords[i] !== "") { // ensure there is a value to highlight
                $('.message p.messagecontent').highlight(arrayOfKeyWords[i]);
            }
        }
    }
    

    Alternatively you could strip the trailing commas if there are any.

    if ($("#searchterm").val().length > 0) {
        $("#searchterm").addClass('marked-purple');
        var arrayOfKeyWords = $("#searchterm").val().replace(/,+$/, '').split(',');
        for (var i = 0; i < arrayOfKeyWords.length; i++) {
            $('.message p.messagecontent').highlight(arrayOfKeyWords[i]);
        }
    }