NoName
NoName

Reputation: 10324

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".

Upvotes: 1

Views: 2856

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

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");

Upvotes: 2

Related Questions