JSFiddle - React, Tailwind, and code Playground
by Jan Petr
HTML
<script src="https://cdn.jsdelivr.net/g/algoliasearch@3(algoliasearchLite.min.js),algoliasearch.helper@2"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" id="search-box" placeholder="Search ..." />
<h2>
Results:
</h2>
<pre id="container">
</pre>
CSS
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
JavaScript
var client = algoliasearch('Y0GJQYP2P4', '0857228f7871c2e81c6e86135a14ddbd');
var helper = algoliasearchHelper(client, 'snippet_test');
search('');
$('#search-box').on('keyup', function() {
search($(this).val());
});
helper.on('result', function(content) {
renderHits(content);
});
function search(q) {
helper.setQuery(q).search();
}
function renderHits(content) {
$('#container').html(syntaxHighlight(JSON.stringify(content, null, 2)));
}
// Only for pretty output of returned JSON
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}