Improving the search: highlighted terms

:  ~ 1 min read

One of the biggest reasons I was pondering to redirect my search to Google's was their bolding of the searched terms. But here's my take on this, keeping the search local:

<%- posts.each do |post|
  date_matches = post[:datetime].match(/(\d{4})-(\d{2})-(\d{2})-(\d{4})/)
  date =[1].to_i, date_matches[2].to_i, date_matches[3].to_i).to_time.utc.to_i
  content = _markdown(post[:body].lines[2..-1].join)
  title = post[:title]
  if defined?(search_terms)
    search_terms.each do |w|
      if content.downcase.index(w)
      	# Saving the original occurrence of the searched term, since the search is done 
        # by ignoring case (downcasing both the search term and the body/title)
        start_index = content.downcase.index(w)
        end_index = start_index + w.length
        original_occurrence = content[start_index..end_index - 1]
        # Then wrapping the original occurrence between a custom tag.
        content.gsub!(original_occurrence, "<search-mark>#{original_occurrence}</search-mark>")
      if title.downcase.index(w)
        start_index = title.downcase.index(w)
        end_index = start_index + w.length
        original_occurrence = title[start_index..end_index - 1]
        title.gsub!(original_occurrence, "<search-mark>#{original_occurrence}</search-mark>")
  end -%>
  <%= erb :post, locals: { date: date, title: title, content: content, link: post[:link]} -%>
<%- end -%>

And here's the CSS for the search-mark tag:

search-mark {
  border-radius: 2px;
  background-color: #fff0f4;
  font-style: normal;

==Easy, peasy!==