I wanted to create a function that converts domains with special characters using pure JavaScript and without any dependencies. However, my function doesn’t seem to provide the correct result. I intended for the converted domain to still be accessible and functional in web browsers.
This is what I have so far
function convertToPunycode(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";
const url2 = "https://алюмика.рф";
const url3 = "https://gebäudehülle.swiss";
console.log(convertToPunycode(url1)); // Expected Output: https://www.xn--anti-rger-z2a.com
console.log(convertToPunycode(url2)); // Expected Output: https://xn--80aaxidg9j.xn--p1ai
console.log(convertToPunycode(url3)); // Expected Output: https://xn--gebudehlle-s5a60a.swiss
2
Answers
Alright, it turns out the code was fine. Thanks to CBroe, it was just the character encoding from which I saved my file. However, the moment I began using an HTML text editor to convert it, it worked perfectly.
Browsers contain a converter; calling
new URL
is 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.