How to print Search Results 'Query' to HTML using JavaScript?

Hi,

Suppose my Search Results URL is

https://example.com/search/?q=Horror+Movies&post_type=product

Normally, I have heading like this.

<h1>Search Results</h1>


However, I want to display search query as per URL parameter q value like this

<h1>Search Results for Horror Movies</h1>

I tried to follow these guide but coudn’t understand

Thanks

Hi,

You can do it using URLSearchParams.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Search Results</title>
</head>
<body>
  <h1>Search Results</h1>

  <script>
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const searchTerm = urlParams.get('q');

    if(searchTerm) {
      const heading = document.querySelector('h1');
      heading.textContent = `Search Results for ${searchTerm}`;
    }
  </script>
</body>
</html>

This will work on all modern browsers.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.