Skip to content

Instantly share code, notes, and snippets.

@BollaBerg
Created March 18, 2024 09:06
Show Gist options
  • Save BollaBerg/ca5e5fbeacfdd2630f3e17e7a0db56d6 to your computer and use it in GitHub Desktop.
Save BollaBerg/ca5e5fbeacfdd2630f3e17e7a0db56d6 to your computer and use it in GitHub Desktop.
Mock and read search parameters (for testing React)
export const mockSearchParams = (params: Record<string, string>) => {
const baseURL = window.location.href.split(/[?#]/)[0];
const formattedParams = Object.entries(params)
.map(([key, value]) => `${key}=${value}`)
.join('&');
window.history.replaceState(null, '', formattedParams ? `${baseURL}?${formattedParams}` : baseURL);
};
export const getSearchParam = (key: string) => new URLSearchParams(window.location.search).get(key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment