Cerin
Cerin

Reputation: 64900

Full-Text Search in Javascript

How would you implement a "poor man's" full text search in Javascript?

I'm implementing a static webpage with no database backend, and the page loads a few thousand records of short text strings via an Ajax JSON load. I'd like the user to be able to efficiently filter these strings via keyword search, ideally with something a little smarter than simply iterating over each string and doing a Javascript .indexOf().

I thought about rendering my JSON to hidden HTML, and using a jQuery DOM search plugin, but I doubt that would be faster than iterating over my JSON list.

Upvotes: 9

Views: 16785

Answers (3)

nonNumericalFloat
nonNumericalFloat

Reputation: 1807

Fuzzy-search variant using Fuse.js instead of Jquery

As you propably also want to have a fuzzy search nowadays. You could use a lib like Fuse.js (demo) to very easily search an array of (nested) objects - this should be as complicated as the "poor mans" approach, but way more effective

E.g. if you have an array ob objects:

[
  {
    "title": "Old Man's War",
    "author": "John Scalzi",
    "tags": ["fiction"]
  },
  {
    "title": "The Lock Artist",
    "author": "Steve",
    "tags": ["thriller"]
  }
]

To search simply use fuse.search('text') after initialization.

const options = {
  includeScore: true,
  // Search in `author` and in `tags` array
  keys: ['author', 'tags']
}

const fuse = new Fuse(list, options)

const result = fuse.search('OldMans War')

See the list of options to limit results.

Upvotes: 1

Yann Thibodeau
Yann Thibodeau

Reputation: 1261

Another solution if you're looking for something very easy to use: ss-search

Upvotes: -2

halfzebra
halfzebra

Reputation: 6807

a few thousand records

This is not that much, have a look at the Full-Text Search in JavaScript with a demo of full-text search in 40k rows.

.indexOf()

JavaScript is a bit limited when it comes to text manipulation, but this will do the job.

Here is a pretty straightforward manual that is perfectly fitting to your question. Jekyll + lunr.js = Static websites with powerful full-text search using JavaScript

I have experience of building static web-pages with smaller amounts of data and usually, performance is the last issue on the way.

Upvotes: 7

Related Questions