aboutsummaryrefslogtreecommitdiff
path: root/src/main.ts
blob: d42da13fb8a19942f6dce334aab7d53e225ae77a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { bangs } from "./bang";

const defaultBang = bangs.find((b) => b.t === "g");

function getBangredirectUrl() {
  const url = new URL(window.location.href);
  const query = url.searchParams.get("q")?.trim() ?? "";
  if (!query) return null;

  const match = query.match(/!([a-z]+)/i);
  if (!match) return null;

  const bangCandidate = match[1].toLowerCase();
  const selectedBang = bangs.find((b) => b.t === bangCandidate) ?? defaultBang;

  // Remove the first bang from the query
  const cleanQuery = query.replace(/![a-z]+\s*/i, "").trim();

  // Format of the url is:
  // https://www.google.com/search?q={{{s}}}
  const searchUrl = selectedBang?.u.replace(
    "{{{s}}}",
    encodeURIComponent(cleanQuery)
  );
  if (!searchUrl) return null;

  return searchUrl;
}

const searchUrl = getBangredirectUrl() ?? "https://www.google.com";

window.location.replace(searchUrl);