Skip to content

Instantly share code, notes, and snippets.

@t-tera
Last active October 6, 2022 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-tera/e8e9d622f433f18d5857f0de4f7ec7f0 to your computer and use it in GitHub Desktop.
Save t-tera/e8e9d622f433f18d5857f0de4f7ec7f0 to your computer and use it in GitHub Desktop.
Check domain of the given URL
// https://www.npmjs.com/package/tr46
const tr46 = require("tr46");
// The function returns NULL if the given URL doesn't have example.jp domain, otherwise it returns URL converted to ASCII.
// No warranty, no license claim.
function chkDomain(url) {
var regex = new RegExp("^(https://)([a-zA-Z0-9\\u0080-\\uDBFF\\uDFFF.-]+)\\.example\\.jp(:\\d{1,5})?(/|$)", "u");
var mt = url.match(regex);
if (!mt) return null;
var prefix = mt[1].toLowerCase();
var subDomain = mt[2];
var port = mt[3] ?? '';
var remaining = url.substring((prefix + subDomain).length);
if (port.length > 0) {
var portNum = Number(port);
if (portNum > 65535) return null;
}
var opts = {checkBidi: true, checkHyphens: true, checkJoiners: true, useSTD3ASCIIRules: true, verifyDNSLength: true};
var ascii = tr46.toASCII(subDomain, opts) ?? '';
if (ascii.length === 0
|| subDomain.split('.').length !== ascii.split('.').length
|| !/^(?!\.)[a-z0-9.-]+(?<!\.)$/.test(ascii)) {
return null;
}
return prefix + ascii + remaining;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment