简体   繁体   中英

Regex for Matching Words within a String

Here is what I have so far, but it only matches the beginning of the target string:

var enteredText = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");

$.ui.autocomplete.filter = function(array, term) {
    var enteredText = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");

    return $.grep(array, function(value) {
        return enteredText.test(value.label || value.value || value);
    });
};

Note: $.ui.autocomplete.filter allows me to change how jQuery UI searches the terms with autocomplete.

"term" is the text entered into the input box.

"$.grep" plugs each element in the autocomplete "array" into "function(value)"

EDIT 1: I'm looking for a Regex to search from the beginning of each word in a string. For example, "an" matches "I like Andy" but not "I like candy".

Here is what I have so far, but it only matches the beginning of the target string:

to address that problem

try this:

Remove ^ since you don't want only at the beginning of the string.

var enteredText = new RegExp($.ui.autocomplete.escapeRegex(term), "i");

And for this:

EDIT 1: I'm looking for a Regex to search from the beginning of each word in a string. For example, "an" matches "I like Andy" but not "I like candy".

Since you say, you want to match, you have to prefix and suffix your regex with .+? . Like

var enteredText = new RegExp(".*"+$.ui.autocomplete.escapeRegex(term)+".*", "i");

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