I wanted to create a function that using pure JavaScript and without any dependencies. However, my function doesn't seem to provide the correct result. I intended for the domain to still be accessible and functional in web browsers.
This is what I have so far
function convrtToP(url) {
const urlObj = new URL(url);
const hostname = urlObj.hostname;
const punycodeHostname = Array.from(hostname)
.map(char => char.match(/[A-Za-z0-9\-._~]/) ? char : `xn--${char.charCodeAt(0).toString(16)}`)
.join('');
urlObj.hostname = punycodeHostname;
return urlObj.href;
}
// Test cases
const url1 = "https://www.anti-ärger.com";
console.log(convrtToP(url1)); // Output: https://www.xn--anti-rger-z2a.com
Browsers contain a converter; calling
new URLis all you need to do. From the console:The map/join call in the question is a no-op because by the time it's called the result is already in the desired format.
The map call is also wildly different from the punycode algorithm; don't even think of implementing punycode with a map like that.