Skip to content

Instantly share code, notes, and snippets.

@ruddra
Created October 25, 2019 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruddra/2cde21d0c4855e405f0af33906b32448 to your computer and use it in GitHub Desktop.
Save ruddra/2cde21d0c4855e405f0af33906b32448 to your computer and use it in GitHub Desktop.
Simple Search hugo
<script>
const posts = {{ $p }};
const query = new URLSearchParams(window.location.search);
const searchString = query.get('q');
document.querySelector('.search-content').innerHTML = searchString;
const $target = document.querySelector('.search-items');
let matchPosts = [];
posts.map(function(p){
const searchStringUp = searchString.toUpperCase();
const fTitle = p.title.toUpperCase().indexOf(searchStringUp);
if (fTitle > -1) {
let score = 10 * fTitle;
score = score + p.content.toUpperCase().indexOf(searchStringUp);
p.score = score;
matchPosts.push(p)
}
})
if (matchPosts.length > 0) {
let matchWithScoreSorted = matchPosts.sort(function(i, j){
return j.score - i.score;
})
console.log(matchWithScoreSorted);
$target.innerHTML = matchWithScoreSorted.map(function(p){
if (p != undefined) {
return `<li>
${p.date} -
<a href="${p.link}"> ${p.title}</a>
</li>`;
}
}).join('');
} else {
$target.innerHTML = `<h2 style="text-align:center">No search results found</h2>`;
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment