1

I think I have all my ducks in order here, I am attempting to search my UL list using brackets either using a left one ( or a right one ) and I am getting a JavaScript kick back error:

"Expected '(' in regular expression".

I am by no means a regex expert here but what exactly could be the problem, i'd like to ideally be able to search using by any letters, numbers or special characters of my choosing in my input box without having the error as I described above.

Using Ie. 11, Fiddle is here: http://jsfiddle.net/acbabis/4cfQ8/show/

jQuery friendly:

$('#refdocs').on('keyup change', function () {
    var search = $(this).val();
    $('#refdocs_list li').each(function () {
        var val = $(this).text();
        $(this).toggle( !! val.match(search)).html(
            val.replace(search, function(match) {return '<span style="background-color: #FFFF00">'+match+'</span>'}, 'gi')
        );
    });
});

enter image description here

user1451890
  • 1,055
  • 2
  • 13
  • 19

3 Answers3

0

Well, if I understand the error correctly, it's because your special characters are getting interpreted as regex function characters, which means they'll need to be escaped. Check out this answer:

Escape string for use in Javascript regex

Community
  • 1
  • 1
Lawrence Johnson
  • 3,924
  • 2
  • 17
  • 30
0

To keep the regex match functionality. You can wrap you .match method inside a try catch block. Also, in order to highlight regex matched results, we have to pass an regex obj into val.replace.

$('#refdocs').on('keyup', function () {
    var search = $(this).val();
    $('#refdocs_list li').each(function () {
        var val = $(this).text();
        try {
            $(this).toggle( !! val.match(search)).html(
            val.replace(new RegExp(search, 'gi'), function (match) {
                return '<mark>' + match + '</mark>'
            }, 'gi'));
        } catch(err) {
            //console.log(err);
        }
    });
});

demo: http://jsfiddle.net/4cfQ8/4/

Fabricator
  • 12,722
  • 2
  • 27
  • 40
0

As @LawrenceJohnson already pointed out, you have to escape any re special characters you wish to use in your search string. The following line shows you how to escape ( and ) but you can extend the list to escape more characters. Take a look at the demo -- url supplied at the bottom:

var search = $(this).val().replace(/([\(\)])/,'\\$1');

The rest of your code was not touched at all.

WORKING JS FIDDLE DEMO

PeterKA
  • 24,158
  • 5
  • 26
  • 48