Reputation: 64900
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
Reputation: 1807
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
Reputation: 1261
Another solution if you're looking for something very easy to use: ss-search
Upvotes: -2
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