Change from subdomain to directory path in geo redirect

I was using a worker to redirect based on country to corresponding language subdomain. However, now I would like to change it to directory. Here’s the code that dictates it to redirec to a subdomain. Could someone please help me with the correct format for converting it to directory instead?

		const lang = countryMap.hasOwnProperty(country) ? countryMap[country] : ''
		const newHostName = `${lang === '' ? '' : lang + '.'}${hostname}`
		if(hostname !== newHostName)
			const redirectUrl = new URL(pathname, `${protocol}//${newHostName}${pathname}`)
			return Response.redirect(redirectUrl.href, 301)

I had tried changing the one line to:

${hostname}${lang === '' ? '' : lang + '/'}

But this either resulted in domain.comen/ or when trying to add a trailing slash in front of en/ it would redirect loop.


Any help to convert it to support the new one would be most appreciated. Thanks!