TypeScript Function Decodes URL Parameters

Angular 2 includes a Routing module that will automatically handle URL parameters that are implicitly passed in a URL.

If you're not using Angular Routing, or if you're passing additional parameters in the URL, you'll need to parse out the query string to retrieve the URL parameters.

Below is a TypeScript function that will return an object with key/value pairs that correspond to the URL parameters passed to a web page. You can optionally pass a query string to decode, or if you pass NULL/don't pass anything, the function will retrieve the query string from the URL of the current web page.

    // parses the query string    parseQueryString(queryString?: string): any {        // if the query string is NULL or undefined        if (!queryString) {            queryString = window.location.search.substring(1);        }        const params = {};        const queries = queryString.split("&");        queries.forEach((indexQuery: string) => {            const indexPair = indexQuery.split("=");            const queryKey = decodeURIComponent(indexPair[0]);            const queryValue = decodeURIComponent(indexPair.length > 1 ? indexPair[1] : "");            params[queryKey] = queryValue;        });        return params;    }