简体   繁体   中英

Basic search functionality with JavaScript

I'm looking for a basic search functionality with JavaScript.

The Scenario : The user enters a single or multiple words, and hit a button. JavaScript looks up in an array of strings for items that probably relates to the entered search sentence.

The only function I'm aware of right now is "string.search" which returns the position of the string you are searching for. This is good, but not for all cases. Here are a few examples the search function should cover

Let's assume I have the following string: "This is a good day" in my array. The following search terms should return true when tested against my search function.

  • Search Term 1: This a good day
  • Search Term 2: This day
  • Search Term 3: This was good
  • Search Term 4: good dy - the user made a typo -

So nothing particular or specific. Just a basic search functionality that predicts (at a low level, and language agnostic) if the search term related to the strings in the tested array.

Was the last a typo for 'day'?

If not, you could simply split the search sentence, as well as the original string using the split() function.

Then you would iterate over the search words and for each make sure they appear in the source string. As soon as you don't find the word, you stop the search.

This is assuming that all the search words should be AND'ed, not OR'ed.

Does that help?

This is not as simple as one would think. We're talking fuzzy matching and Levenshtein distance / algorithm.

See this past question: Getting the closest string match

I guess what you are looking for is a pattern matching based live search similar to finite-state-automata-like (FSA) searching:

This link shows an example that'll allow you to search case-insensitively:

Example: Array contains 'This is a good day'

Searching for any (or all) of the following is valid:

  • THis a Day
  • Thagd ( Th is a g oo d day)
  • good dy -intended typo-

etc.

A case-sensitive (albeit not perfect FSA based) version can be found here There is also one by John Resig but I don't have a link to his demo but it'd be worth looking at - it's a javascript/jquery port of the first link I mentioned.

Hope this helps!

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