0

I'm trying to highlight a searched terms which is working well. The problem is that I would like to avoid having 1 or 2 character words or "the" and 'and.'

if I use

var term = $('#q').val().split(/\s+/);
     if(term.length < 3){
    $('p').highlight(term);
     }

it will take the input value as a whole string, so it has more then 3 letters.

so I guess I need to use

if(term:contains('and')){}

but the trick is how will I un-highlight that?

demo

1

2 Answers 2

1

You checked the length of the string array and not actually the length of each string, this should work:

 $(document).ready(function() {

    var term = $('#q').val().split(/\s+/);
    for(var i=0;i<term.length;i++)
    { 
       if(term[i].length > 3)
        $('p').highlight(term[i]);      
    }          
 });

FIDDLE http://jsfiddle.net/eayan/16/

UPDATE: To allow terms set up one array of allowed words i.e:

var allowed = ["xp","try"];   

change the if to:

if(term[i].length > 3 || $.inArray(term[i],allowed) >= 0)

for case insensitive search you gotta make some tunes

Fiddle - allowed words

Sign up to request clarification or add additional context in comments.

3 Comments

is there a way to exclude some words that I need to highlight but have less letters. ie XP?
I see some problem because "by" is also highlighted and it shouldn't be because is less then 3 letters
sorry, the result of inArray must be >= so means it was found
1

You can replace remove the words you don't want:

var term = $("#q").val();

var unwantedWords = ['the', 'and', 'this', 'that', 'a', 'an'];

// remove unwanted words 
for (var i = 0; i < unwantedWords.length; i++) {
    term = term.replace(new RegExp("\\s+" + unwantedWords[i]), "");
}

term = term.split(/\s+/);

$('p').highlight(term);

Updated Fiddle

5 Comments

excelent, thanks a lot. I wish if I could give two good answers!
one more question though. How would I do opposite. Now I hide the words smaller then 3 letters but if I need some words that have only 2 letters?
@SamotnyPocitac See my updated solution. You can create an array of unwanted words, and remove each of them. This makes is a bit more extensible; if you uncover additional words you don't want, you can just add them to the array. It also means that it isn't dependent on the length of the word, but on the word itself (e.g. article adjetives, etc.);
that doesn't seem to work, you can even see in your demo that and is highlighted
@SamotnyPocitac There was a syntax error. JSHint ftw. Updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.