Search words in any order using JS

落爺英雄遲暮 提交于 2019-12-11 08:16:39

问题


I have code to search the typed words from the text box, Get the typed word, search it in the web sql database and show the result in the HTML page.

In that i can search the word exactly as it is, using LIKE.

(i.e)

SELECT * FROM tblName WHERE SearchWord LIKE %<typedword>%

If the table has,

  1. Hello Doctor
  2. Hi Sir
  3. Hello World
  4. Welcome Programmer

And the user types as "Hello", it shows me

**Hello** Doctor
**Hello** World

I need to display the result even if the user wrongly arranges the words,

i.e If the user types as "World Hello"

It is not showing any results. But, I want to show the user

Hello World

Can you please help me?


回答1:


So you want an AND search using each of the words entered, rather than the exact string? Howabout something like this:

var yourSearchText = 'World Hello';
var searchTerms = yourSearchText.split(' ');
var searchTermBits = [];
for(var i=0; i<searchTerms.length;i++) {
        searchTermBits.push("word LIKE %"+searchTerms[i]+"%");
}

var result = searchTermBits.join(" AND ");
var query = 'SELECT * FROM TABLE WHERE '+result;

this will give you a query like:

SELECT * FROM table WHERE word LIKE '%world%' AND word LIKE '%hello%'

change the AND to an OR if you want to match any of the search terms rather than all.



来源:https://stackoverflow.com/questions/22295205/search-words-in-any-order-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!