I am working on predicting the search from an input.
Many searches will start with year/make/model of a car PLUS the part they are searching for
I would love if it was possible to predict after the year/make/model (or even anywhere inside the input after any text) but I'm not sure how to achieve this
eg: 2002 Honda S2000 Brake Ro
It should be able to compare "brake ro" to get "brake rotor" from the set of data
function predictSearch(input) {
const results = [];
for (i = 0; i < predictiondata.length; i ) {
if(input.toLowerCase() === predictiondata[i].slice(0, input.length).toLowerCase()) {
if(results.length < 5) {
results.push(predictiondata[i].toLowerCase());
}
}
}
return results;
}
I have this but it specifically looks for the prediction data starting from the beginning of the input
CodePudding user response:
Are you using an SQL database to store the part names?
For a live search in an SQL db with ajax, in your SQL statement you can place percent signs (%) around the variable posted by the ajax, this will search the part names list for any matches to the string pattern from the input, the % signs allow it to check inside of the db's strings for any matches as well.
This video helped me in a similar situation https://www.youtube.com/watch?v=wCsPAquMNVw&t=2s
CodePudding user response:
Rather than interpolating each string to determine if there's a match, it might be worth considering regex.test() to check if each predictiondata
contains input
anywhere.
function predictSearch(input) {
const results = [];
const regex = new RegExp(`${input}*`);
for (i = 0; i < predictiondata.length; i ) {
// Check if input is in predictiondata[i]
if (regex.test(predictiondata[i])) {
if (results.length < 5) {
results.push(predictiondata[i].toLowerCase());
}
}
}
return results;
}