Parse URL query strings with Cloudflare Workers

Again, something simple that could be handy in many scenarios.

addEventListener('fetch', event => {
	event.passThroughOnException() // Optional; you know best
	event.respondWith(handleRequest(event.request))
})

/**
 * Fetch and log a given request object
 * @param {Request} request
 */
async function handleRequest(request) {
	const url = request.url

	// Function to parse query strings
	function getParameterByName(name) {
		name = name.replace(/[\[\]]/g, '\\$&')
		name = name.replace(/\//g, '')
		var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
			results = regex.exec(url)

		if (!results) return null
		else if (!results[2]) return ''
		else if (results[2]) {
			results[2] = results[2].replace(/\//g, '')
		}
		
		return decodeURIComponent(results[2].replace(/\+/g, ' '));
	}

	// Usage example
	var test = getParameterByName('test')
	console.log(test)

	// Do your work
	// ...

	// Send on the response
	const response = await fetch(request)
	return response
}