简体   繁体   中英

Javascript regex for words including spaces and other characters

String search : 'authorizations'

Actual :

Authorizations

PCP / Authorizations

Expected is :

Authorizations

PCP / Authorizations

I am trying to bold the search results, but I want to bold only the exact matches. I used this regex but it does not gives the desired result.

        $(event.target).autocomplete({
                        minLength: 1,
                        source: $(event.target).attr("data-source").replace("[","").replace("]","").split(",")
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var term = this.term,
                regex = new RegExp('\\b' + term + '\\b', 'gi');
                label = item.label.replace(regex, '<b style="font-weight: bold;">$&</b>');
                $link = $("<a></a>").html(label);
            return $("<li></li>").append($link).appendTo(ul);
        };

Since you only want to bold on exact equivalence, then why not just use == to compare the string:

    $(event.target).autocomplete({
                    minLength: 1,
                    source: $(event.target).attr("data-source").replace("[","").replace("]","").split(",")
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
        var term = this.term;
        if (item.label == 'Authorizations') {
            label = '<b style="font-weight: bold;">Authorizations</b>';
        }
        else {
            label = item.label;
        }
        $link = $("<a></a>").html(label);

        return $("<li></li>").append($link).appendTo(ul);
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM