javascriptjquery-tokeninput

How to fix such RegExp bug in jQuery plugin?


I am using jQuery Tokeninput autocomplete plugin for the list of programming languages and I have found out, that it does not handle a "+" character in "C++": it returns a JavaScript error and nothing appears on autocomplete list.

When I enter "C" ir returns the error:

Uncaught SyntaxError: Invalid regular expression: /(?![^&;]+;)(?!<[^<>])(C++)(?![^<>]>)(?![^&;]+;)/: Nothing to repeat

The problem seems to be in a small method with RegExp statement:

function find_value_and_highlight_term(template, value, term) {
    return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}

Variables:

template = "<li>C++</li>";
value = "C++";
term = "C";

How do I fix it?


Solution

  • + is a special modifier in regexes which means "match one or more of the previous thing". To match against a literal '+' character, escape it with a \

    /(?![^&;]+;)(?!<[^<>])(C\+\+)(?![^<>]>)(?![^&;]+;)/
    

    To escape all special characters:

    function escapeRegex(str) {
      return str.replace(/[-\/\\$\^*+?.()|\[\]{}]/g, '\\$&');
    }
    
    var re = new RegExp(escapeRegex('[.*?]'));