SKU to Predictive Search - Dawn theme - 2023

Update for Dawn version 15.4.0

the above code won’t work because the regular expression in the js can’t handle the special characters in the new URL. The issue is in the updateSearchForTerm() method around line 108 inside assets/predictive-search.js

Replace with:

updateSearchForTerm(previousTerm, newTerm) {
  const searchForTextElement = this.querySelector('[data-predictive-search-search-for-text]');
  const currentButtonText = searchForTextElement?.innerText;
  if (currentButtonText) {
    // Escape special regex characters in previousTerm
    const escapedPreviousTerm = previousTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const matches = currentButtonText.match(new RegExp(escapedPreviousTerm, 'g'));
    if (matches && matches.length > 1) {
      // The new term matches part of the button text and not just the search term, do not replace to avoid mistakes
      return;
    }
    const newButtonText = currentButtonText.replace(previousTerm, newTerm);
    searchForTextElement.innerText = newButtonText;
  }
}

Then update the fetch request

   fetch(`${routes.predictive_search_url}?q=${encodeURIComponent(searchTerm)}&resources[type]=product,collection,page,article&resources[options][fields]=title,product_type,variants.title,variants.sku,vendor&section_id=predictive-search`, {
      signal: this.abortController.signal,
    })

Bonus - Add SKU in the suggestions drawer for better customer clarity

Modify sections/predictive-search.liquid and add SKU after the product title.

<p class="predictive-search__item-heading h5">{{ product.title | escape }}</p>

{%- if product.selected_or_first_available_variant.sku != blank -%}
  <div class="predictive-search__item-sku caption-with-letter-spacing">
    <span class="visually-hidden">{{ 'products.product.sku' | t }}: </span>
    SKU: {{ product.selected_or_first_available_variant.sku }}
  </div>
{%- endif -%}