3

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

2 Answers 2

4

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]); } } 
Sign up to request clarification or add additional context in comments.

Comments

1

Thats how you can remove last comma of a string:

var str = "stack,overflow,js,"; if(str.charAt( str.length-1 ) == ",") { str = str.slice(0, -1); } 

1 Comment

The question is how to ignore the last comma!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.