Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find exact string with no more or less

Tags:

jquery

regex

I have some text from a breadcrumb which I am using to open menu items on a page. For example, say the bctext = 'pasta'.

I want to target the word "pasta", but not say "yadda yadda yadda pasta". Only an instance of the single word "pasta" should match, or if bctext were a phrase, then it would only find the exact phrase.

This is what I have so far:

$('ul#accordion a:contains(' + bctext + ')')

But this finds "yadda yadda pasta", of course.

I get the bctext with the following:

var bctext = $('#CategoryBreadcrumb ul li:last-child').prev().children().text();

Then, I edit the menu with the following:

$('ul#accordion a:contains(' + bctext + ')').parent()
                                            .addClass('special')
                                            .children('ul')
                                            .css('display','block'); 

Is what I'm going for possible?

like image 315
liz Avatar asked Apr 30 '12 17:04

liz


1 Answers

$('ul#accordion a').filter(function() {
    return $(this).text() == bctext;
}).parent().addClass('special').children('ul').css('display','block');

:contains() is not a native selector anyway so using .filter() with a custom callback won't have any performance drawbacks.

like image 57
ThiefMaster Avatar answered Nov 09 '22 20:11

ThiefMaster