Search code examples
javascriptjqueryregexlookbehind

javascript regex lookbehind and jQuery selector


I am using the following regex in a custom selector in jQuery

$.expr[":"].matchRegex = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match(new RegExp(arg, 'i')) != null;
    };
});

However, since javascript does not allow lookbehind, I am unable to pass this regex:

/\b(?<!')(s|otherword)s?\b/

The expression should match at least one s if it not preceded by a single quote. The s|otherword part in the expression is actually provided by the user, so I have to work with that.

I understand how creating a custom function (Javascript: negative lookbehind equivalent?) can be a workaround for the lookbehind (replace example) but I am unable to get this to work.

I tried modifying my selector to this:

$.expr[":"].matchRegex = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return ($(elem).text().match(new RegExp(arg, 'i')) != null) ? false : true;
    };
});

and changing the regex expression to this:

/\b(')(s|otherword)s?\b/

but this will return all elements with text that do not contain 's.

Can I use the match method with a callback function? If not, how can the jQuery selector be modified to accommodate this?

Any insight and help always greatly appreciated.

Thank you!


Solution

  • The expression should match at least one s if it not preceded by a single quote.

    Since you really don't want to work with the matches, only test if there is a match at all, you don't really need a lookbehind. You only need to make sure that it works at the start of the string.

    (?:^|[^'])(s|otherword)s?\b
    

    That's all, really.