Skip to content

Instantly share code, notes, and snippets.

@mumy81
Last active February 20, 2020 21:13
Show Gist options
  • Save mumy81/ffc1a427d71a0e7070bfa9736a4440f2 to your computer and use it in GitHub Desktop.
Save mumy81/ffc1a427d71a0e7070bfa9736a4440f2 to your computer and use it in GitHub Desktop.
JS Regex
I have solved this regex problem for :
https://www.codewars.com/kata/514a024011ea4fb54200004b
Find domain name in URLs with subdomains or without subdomains :
Regex : /((\w*:)?(\/\/)?(www\.)?)?([\w-]+\.)?(\w{2,}[\w-]+)\./g
function domainName(url){
var re = /((\w*:)?(\/\/)?(www\.)?)?([\w-]+\.)?(\w{2,}[\w-]+)\./g;
var arr = re.exec(url);
return arr[arr.length-1];
}
//Output:
http://github.com/carbonfive/raygun ==> github
http://www.zombie-bites.com ==> zombie-bites
www.zuonegwr3vrhsjmtir07qwup.tv/default ==> uonegwr3vrhsjmtir07qwup
asdsad.wewewe-wewr.com ==> wewewe-wewr
ftp://wewe.sadg.cdfdfdgfg.co ==> cdfdfdgfg
asdsad.fgfdgf.okk.te ==> okk
www.google.co.uk ==> google
From: https://www.codewars.com/kata/514a024011ea4fb54200004b/solutions/javascript/all/best_practices
1.
function domainName(url){
url = url.replace("https://", '');
url = url.replace("http://", '');
url = url.replace("www.", '');
return url.split('.')[0];
};
2.
function domainName(url){
return url.match(/(?:http(?:s)?:\/\/)?(?:w{3}\.)?([^\.]+)/i)[1];
}
3.
function domainName(url){
return url.replace(/(https?:\/\/)?(www\.)?/, '').split('.')[0]
}
4.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment