I have an input that searches a database with jQuery autocomplete. It’s working well but I want it to be more permissive with some characters. Let’s say in the database the data is : oc-5 I need the requested string oc5 or oc_5 to match the current string in the database.
Same if the current value in the database is ac2, I need a-c-2 or ac_2 or ac-2 or ac 2 to match the value.
Actually, I want the characters “-“, “_” and ” ” to act like a wildcard.
I guess I have to regex my request.term but I’m not sure how to do it.
Here’s my code :
$(".autocomplete").autocomplete({
delay: 100,
source: function (request, response) {
// Suggest URL
var datatype = this.element.attr('data-type');
var suggestURL = href+"&datatype="+datatype+"&term="+request.term;
// JSONP Request
$.ajax({
method: 'POST',
url: suggestURL
})
.success(function(data){
response(data);
});
}
});
2
Answers
Consider the following code:
You can update the Term before sending it and remove any of the
"-"
,"_"
, or" "
characters from the string with.replace()
using a Regular Expression.Working Example.
Since you want to go both ways, you could check if the two values match after using a replace, if so make the request value equal the database value.
where
db_val
is your database value andrq_val
is the sent request value.If you don’t want to allow one of the listed special characters at the beginning or end of the string, and you don’t to allow multiple special characters in a row, you could rather use this regex:
.replace(/^(?:[^-_s][-_s]?){3}(?<![-_s])$/, "")
. This means check for any character excluding the specials followed by a special repeated three times, and makes sure the end of the string is not preceded by a special.I’m not great at regex but that’s what I came up with.