Created
October 25, 2019 16:16
-
-
Save ruddra/2cde21d0c4855e405f0af33906b32448 to your computer and use it in GitHub Desktop.
Simple Search hugo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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