How to get domain name only using javascript? - javascript

I want to get domain name only using javascript. Ex
vn.search.yahoo.com -> yahoo
vn.search.yahoo.com.vn -> yahoo
sub1.sub2.sub3.abcdef.co.uk -> abcdef
Thank you!
Edit: "domain" = domain without extension (ex: .com, .net, .co.uk...) and without sub domain (ex: www, email, cdn, support...)

Use location.host and cut off subdomains and the TLD:
var domain = (location.host.match(/([^.]+)\.\w{2,3}(?:\.\w{2})?$/) || [])[1]
update: as #demix pointed out, this fails for 2 and 3-letter domains. It also won't work for domains like aero, jobs and dozens others.
The only way around is to know valid TLDs in advance, so here is a more appropriate function:
// http://data.iana.org/TLD/tlds-alpha-by-domain.txt
var TLDs = ["ac", "ad", "ae", "aero", "af", "ag", "ai", "al", "am", "an", "ao", "aq", "ar", "arpa", "as", "asia", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "biz", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cat", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "com", "coop", "cr", "cu", "cv", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "edu", "ee", "eg", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gov", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "info", "int", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jobs", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mil", "mk", "ml", "mm", "mn", "mo", "mobi", "mp", "mq", "mr", "ms", "mt", "mu", "museum", "mv", "mw", "mx", "my", "mz", "na", "name", "nc", "ne", "net", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "org", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "pro", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "su", "sv", "sy", "sz", "tc", "td", "tel", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tp", "tr", "travel", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "xn--0zwm56d", "xn--11b5bs3a9aj6g", "xn--3e0b707e", "xn--45brj9c", "xn--80akhbyknj4f", "xn--90a3ac", "xn--9t4b11yi5a", "xn--clchc0ea0b2g2a9gcd", "xn--deba0ad", "xn--fiqs8s", "xn--fiqz9s", "xn--fpcrj9c3d", "xn--fzc2c9e2c", "xn--g6w251d", "xn--gecrj9c", "xn--h2brj9c", "xn--hgbk6aj7f53bba", "xn--hlcj6aya9esc7a", "xn--j6w193g", "xn--jxalpdlp", "xn--kgbechtv", "xn--kprw13d", "xn--kpry57d", "xn--lgbbat1ad8j", "xn--mgbaam7a8h", "xn--mgbayh7gpa", "xn--mgbbh1a71e", "xn--mgbc0a9azcg", "xn--mgberp4a5d4ar", "xn--o3cw4h", "xn--ogbpf8fl", "xn--p1ai", "xn--pgbs0dh", "xn--s9brj9c", "xn--wgbh1c", "xn--wgbl6a", "xn--xkc2al3hye2a", "xn--xkc2dl3a5ee0h", "xn--yfro4i67o", "xn--ygbi2ammx", "xn--zckzah", "xxx", "ye", "yt", "za", "zm", "zw"].join()
function getDomain(url){
var parts = url.split('.');
if (parts[0] === 'www' && parts[1] !== 'com'){
parts.shift()
}
var ln = parts.length
, i = ln
, minLength = parts[parts.length-1].length
, part
// iterate backwards
while(part = parts[--i]){
// stop when we find a non-TLD part
if (i === 0 // 'asia.com' (last remaining must be the SLD)
|| i < ln-2 // TLDs only span 2 levels
|| part.length < minLength // 'www.cn.com' (valid TLD as second-level domain)
|| TLDs.indexOf(part) < 0 // officialy not a TLD
){
return part
}
}
}
getDomain(location.host)
I hope I didn't miss too many corner cases. This should be available in the location object :(
Test cases: http://jsfiddle.net/hqBKd/4/
A list of TLDs can be found here: http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1

I was looking for something that would work for the majority of cases, without having to maintain the TLD list (and skip it's size!). It seems to me that you can do this pretty accurately by looking instead at the Second-Level Domain for common ones:
function getDomainName(domain) {
var parts = domain.split('.').reverse();
var cnt = parts.length;
if (cnt >= 3) {
// see if the second level domain is a common SLD.
if (parts[1].match(/^(com|edu|gov|net|mil|org|nom|co|name|info|biz)$/i)) {
return parts[2] + '.' + parts[1] + '.' + parts[0];
}
}
return parts[1]+'.'+parts[0];
}
Fiddle & Tests # http://jsfiddle.net/mZPaf/2/
Critiques/thoughts welcome.

var docdomain = document.domain.split('.');
var dom1 = "";
if (typeof (docdomain[docdomain.length - 2]) != 'undefined') dom1 = docdomain[docdomain.length - 2] + '.';
var domain = dom1 + docdomain[docdomain.length - 1];
console.log(domain);
//without subdomains

The only way I can imagine is list all the TLD. Sample code like below.
function getDomainName(){
var domainList = ['com','org','net',...];//all TLD
var tokens = document.domain.split('.');
while(tokens.length){
var token = tokens.pop();
if( domainList.indexOf(token) == -1 ){
return token;
}
}
return null;
}
Array.prototype.indexOf should do some fix in IE.

Without having a complete list of TLD's (which would get very long). If you just need the domain name from the current page you can use my technique (using cookies to find the root domain)
Javascript - Get Domain Name Excluding Subdomain
To remove the extension you can then use the first element from a str.split('.')[0]

It's simple:
var tokens = document.domain.split('.');
var domain = tokens[tokens.length - 2];

i needed to do this and whipped up something simple that accounted for my use case
function stripSubDomainAndTLD (domain) {
return domain.replace(/^(?:[a-z0-9\-\.]+\.)??([a-z0-9\-]+)(?:\.com|\.net|\.org|\.biz|\.ws|\.in|\.me|\.co\.uk|\.co|\.org\.uk|\.ltd\.uk|\.plc\.uk|\.me\.uk|\.edu|\.mil|\.br\.com|\.cn\.com|\.eu\.com|\.hu\.com|\.no\.com|\.qc\.com|\.sa\.com|\.se\.com|\.se\.net|\.us\.com|\.uy\.com|\.ac|\.co\.ac|\.gv\.ac|\.or\.ac|\.ac\.ac|\.af|\.am|\.as|\.at|\.ac\.at|\.co\.at|\.gv\.at|\.or\.at|\.asn\.au|\.com\.au|\.edu\.au|\.org\.au|\.net\.au|\.id\.au|\.be|\.ac\.be|\.adm\.br|\.adv\.br|\.am\.br|\.arq\.br|\.art\.br|\.bio\.br|\.cng\.br|\.cnt\.br|\.com\.br|\.ecn\.br|\.eng\.br|\.esp\.br|\.etc\.br|\.eti\.br|\.fm\.br|\.fot\.br|\.fst\.br|\.g12\.br|\.gov\.br|\.ind\.br|\.inf\.br|\.jor\.br|\.lel\.br|\.med\.br|\.mil\.br|\.net\.br|\.nom\.br|\.ntr\.br|\.odo\.br|\.org\.br|\.ppg\.br|\.pro\.br|\.psc\.br|\.psi\.br|\.rec\.br|\.slg\.br|\.tmp\.br|\.tur\.br|\.tv\.br|\.vet\.br|\.zlg\.br|\.br|\.ab\.ca|\.bc\.ca|\.mb\.ca|\.nb\.ca|\.nf\.ca|\.ns\.ca|\.nt\.ca|\.on\.ca|\.pe\.ca|\.qc\.ca|\.sk\.ca|\.yk\.ca|\.ca|\.cc|\.ac\.cn|\.com\.cn|\.edu\.cn|\.gov\.cn|\.org\.cn|\.bj\.cn|\.sh\.cn|\.tj\.cn|\.cq\.cn|\.he\.cn|\.nm\.cn|\.ln\.cn|\.jl\.cn|\.hl\.cn|\.js\.cn|\.zj\.cn|\.ah\.cn|\.gd\.cn|\.gx\.cn|\.hi\.cn|\.sc\.cn|\.gz\.cn|\.yn\.cn|\.xz\.cn|\.sn\.cn|\.gs\.cn|\.qh\.cn|\.nx\.cn|\.xj\.cn|\.tw\.cn|\.hk\.cn|\.mo\.cn|\.cn|\.cx|\.cz|\.de|\.dk|\.fo|\.com\.ec|\.tm\.fr|\.com\.fr|\.asso\.fr|\.presse\.fr|\.fr|\.gf|\.gs|\.co\.il|\.net\.il|\.ac\.il|\.k12\.il|\.gov\.il|\.muni\.il|\.ac\.in|\.co\.in|\.org\.in|\.ernet\.in|\.gov\.in|\.net\.in|\.res\.in|\.is|\.it|\.ac\.jp|\.co\.jp|\.go\.jp|\.or\.jp|\.ne\.jp|\.ac\.kr|\.co\.kr|\.go\.kr|\.ne\.kr|\.nm\.kr|\.or\.kr|\.li|\.lt|\.lu|\.asso\.mc|\.tm\.mc|\.com\.mm|\.org\.mm|\.net\.mm|\.edu\.mm|\.gov\.mm|\.ms|\.nl|\.no|\.nu|\.pl|\.ro|\.org\.ro|\.store\.ro|\.tm\.ro|\.firm\.ro|\.www\.ro|\.arts\.ro|\.rec\.ro|\.info\.ro|\.nom\.ro|\.nt\.ro|\.se|\.si|\.com\.sg|\.org\.sg|\.net\.sg|\.gov\.sg|\.sk|\.st|\.tf|\.ac\.th|\.co\.th|\.go\.th|\.mi\.th|\.net\.th|\.or\.th|\.tm|\.to|\.com\.tr|\.edu\.tr|\.gov\.tr|\.k12\.tr|\.net\.tr|\.org\.tr|\.com\.tw|\.org\.tw|\.net\.tw|\.ac\.uk|\.uk\.com|\.uk\.net|\.gb\.com|\.gb\.net|\.vg|\.sh|\.kz|\.ch|\.info|\.ua|\.gov|\.name|\.pro|\.ie|\.hk|\.com\.hk|\.org\.hk|\.net\.hk|\.edu\.hk|\.us|\.tk|\.cd|\.by|\.ad|\.lv|\.eu\.lv|\.bz|\.es|\.jp|\.cl|\.ag|\.mobi|\.eu|\.co\.nz|\.org\.nz|\.net\.nz|\.maori\.nz|\.iwi\.nz|\.io|\.la|\.md|\.sc|\.sg|\.vc|\.tw|\.travel|\.my|\.se|\.tv|\.pt|\.com\.pt|\.edu\.pt|\.asia|\.fi|\.com\.ve|\.net\.ve|\.fi|\.org\.ve|\.web\.ve|\.info\.ve|\.co\.ve|\.tel|\.im|\.gr|\.ru|\.net\.ru|\.org\.ru|\.hr|\.com\.hr)$/, '$1');
}
mainly i just wanted to remove all subdomains, unfortunately this isn't 100% for some of the new TLD's but it works pretty well, and you can always add to the regex.
http://jsfiddle.net/icodeforlove/TzjJE/2/

With the help of other friend's code examples given above I created a function which will return only domain name and if it is not valid domain for example TLD is missing then it will attach ".com" as per my requirement.
function getDomain(url){
var TLDs = ["ac", "ad", "ae", "aero", "af", "ag", "ai", "al", "am", "an", "ao", "aq", "ar", "arpa", "as", "asia", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "biz", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cat", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "com", "coop", "cr", "cu", "cv", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "edu", "ee", "eg", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gov", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "info", "int", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jobs", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mil", "mk", "ml", "mm", "mn", "mo", "mobi", "mp", "mq", "mr", "ms", "mt", "mu", "museum", "mv", "mw", "mx", "my", "mz", "na", "name", "nc", "ne", "net", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "org", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "pro", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "su", "sv", "sy", "sz", "tc", "td", "tel", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tp", "tr", "travel", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "xn--0zwm56d", "xn--11b5bs3a9aj6g", "xn--3e0b707e", "xn--45brj9c", "xn--80akhbyknj4f", "xn--90a3ac", "xn--9t4b11yi5a", "xn--clchc0ea0b2g2a9gcd", "xn--deba0ad", "xn--fiqs8s", "xn--fiqz9s", "xn--fpcrj9c3d", "xn--fzc2c9e2c", "xn--g6w251d", "xn--gecrj9c", "xn--h2brj9c", "xn--hgbk6aj7f53bba", "xn--hlcj6aya9esc7a", "xn--j6w193g", "xn--jxalpdlp", "xn--kgbechtv", "xn--kprw13d", "xn--kpry57d", "xn--lgbbat1ad8j", "xn--mgbaam7a8h", "xn--mgbayh7gpa", "xn--mgbbh1a71e", "xn--mgbc0a9azcg", "xn--mgberp4a5d4ar", "xn--o3cw4h", "xn--ogbpf8fl", "xn--p1ai", "xn--pgbs0dh", "xn--s9brj9c", "xn--wgbh1c", "xn--wgbl6a", "xn--xkc2al3hye2a", "xn--xkc2dl3a5ee0h", "xn--yfro4i67o", "xn--ygbi2ammx", "xn--zckzah", "xxx", "ye", "yt", "za", "zm", "zw"].join()
url = url.replace(/.*?:\/\//g, "");
url = url.replace(/www./g, "");
var parts = url.split('/');
url = parts[0];
var parts = url.split('.');
if (parts[0] === 'www' && parts[1] !== 'com'){
parts.shift()
}
var ln = parts.length
, i = ln
, minLength = parts[parts.length-1].length
, part
// iterate backwards
while(part = parts[--i]){
// stop when we find a non-TLD part
if (i === 0 // 'asia.com' (last remaining must be the SLD)
|| i < ln-2 // TLDs only span 2 levels
|| part.length < minLength // 'www.cn.com' (valid TLD as second-level domain)
|| TLDs.indexOf(part) < 0 // officialy not a TLD
){
var actual_domain = part;
break;
//return part
}
}
//console.log(actual_domain);
var tid ;
if(typeof parts[ln-1] != 'undefined' && TLDs.indexOf(parts[ln-1]) >= 0)
{
tid = '.'+parts[ln-1];
}
if(typeof parts[ln-2] != 'undefined' && TLDs.indexOf(parts[ln-2]) >= 0)
{
tid = '.'+parts[ln-2]+tid;
}
if(typeof tid != 'undefined')
actual_domain = actual_domain+tid;
else
actual_domain = actual_domain+'.com';
return actual_domain;
}

You could use document.domain to determine the domain name of the current page.
When setting document.domain, an error is thrown if the new value is invalid. A plain eTLD is invalid, while an eTLD+1 is valid. The function below loops to find a valid value, then returns the domain name portion.
This is comprehensive, because the browser uses the Public Suffix List to validate new values.
function getDomainName() {
const original = document.domain;
const parts = location.hostname.split('.');
let etld = parts.pop();
while (parts.length) {
const name = parts.pop();
const test = name + '.' + etld;
try {
document.domain = test;
// we found the eTLD+1
// reset before returning
document.domain = original;
return name;
} catch (e) {
// eTLDs and eTLD fragments fail
etld = test;
}
}
}

What about this?
function getDomain(){
if(document.domain.length){
var parts = document.domain.replace(/^(www\.)/,"").split('.');
//is there a subdomain?
while(parts.length > 2){
//removing it from our array
var subdomain = parts.shift();
}
//getting the remaining 2 elements
var domain = parts.join('.');
return domain.replace(/(^\.*)|(\.*$)/g, "");
}
return '';
}

RegEx I use to get domain name only: ([^.]*[.]){0,}([^.]*)(\.[^.]*)
The domain can be found in the second part.

function getDomainName( hostname ) {
var TLDs = new RegExp(/\.(com|net|org|biz|ltd|plc|edu|mil|asn|adm|adv|arq|art|bio|cng|cnt|ecn|eng|esp|etc|eti|fot|fst|g12|ind|inf|jor|lel|med|nom|ntr|odo|ppg|pro|psc|psi|rec|slg|tmp|tur|vet|zlg|asso|presse|k12|gov|muni|ernet|res|store|firm|arts|info|mobi|maori|iwi|travel|asia|web|tel)(\.[a-z]{2,3})?$|(\.[^\.]{2,3})(\.[^\.]{2,3})$|(\.[^\.]{2})$/);
return hostname.replace(TLDs, '').split('.').pop();
}
/* TEST */
var domains = [
'domain.com',
'subdomain.domain.com',
'www.subdomain.domain.com',
'www.subdomain.domain.info',
'www.subdomain.domain.info.xx',
'mail.subdomain.domain.co.uk',
'mail.subdomain.domain.xxx.yy',
'mail.subdomain.domain.xx.yyy',
'mail.subdomain.domain.xx',
'domain.xx'
];
var result = [];
for (var i = 0; i < domains.length; i++) {
result.push( getDomainName( domains[i] ) );
}
alert ( result.join(' | ') );
// result: domain | domain | domain | domain | domain | domain | domain | domain | domain | domain

Related

How to add dynamic object as a nested object to another object - javascript

I am fetching data from an API and structuring it in constant res.
Now using a nested for loop, to get the devices and countries, creating a variable adding those names, and then want to add all the data that has the device name and country name to another object.
The output I want to achieve should look like this:
{
"GEO_Device": {
"masterID": {
"appID": "1490262670",
"cvr": "51.06666666666667",
"name": "Hard Rock Blackjack",
"anchor": "Hard Rock Blackjack",
"short_desc": "Complete Task to Earn!",
"long_desc": "Discover the world of online Hard Rock Casino games!",
"revenue": "0.45",
"image": "https://cdn.adgem.com/campaigns/12119/campaign-offerwall-creatives/icons/202106252106.jpg",
"geo": [
"DE",
"FR",
"FI",
"DK",
"CZ",
"GB",
"CH",
"SE",
"ES",
"PT",
"NO",
"NL",
"HU",
"IT",
"GR"
],
"masterID": "adGem12119",
"devices": [
"ipad",
"iphone"
],
"link": "https://api.adgem.com/v1/click?all=1&appid=4746&cid=12119&playerid={playerid}",
"reward": "nothing",
"source": "adgem",
"isPromoted": true,
"priority": "1",
"isDisabled": false,
"forceType": "null"
},
"masterID2": {
"appID": "1490262670",
"cvr": "51.06666666666667",
"name": "Hard Rock Blackjack",
"anchor": "Hard Rock Blackjack",
"short_desc": "Complete Task to Earn!",
"long_desc": "Discover the world of online Hard Rock Casino games!",
"revenue": "0.45",
"image": "https://cdn.adgem.com/campaigns/12119/campaign-offerwall-creatives/icons/202106252106.jpg",
"geo": [
"DE",
"FR",
"FI",
"DK",
"CZ",
"GB",
"CH",
"SE",
"ES",
"PT",
"NO",
"NL",
"HU",
"IT",
"GR"
],
"masterID": "adGem12119",
"devices": [
"ipad",
"iphone"
],
"link": "https://api.adgem.com/v1/click?all=1&appid=4746&cid=12119&playerid={playerid}",
"reward": "nothing",
"source": "adgem",
"isPromoted": true,
"priority": 1,
"isDisabled": false,
"forceType": "null"
}
}
}
But instead of that, I am only getting one data added to the object and others are being overwritten. See below:
{
"GEO_DeviceName": {
"appID": "uu32mdnnsjns",
"cvr": 51.06666666666667,
"name": "Hard Rock Blackjack",
"anchor": "Hard Rock Blackjack",
"short_desc": "Complete Task to Earn!",
"long_desc": "Discover the world of online Hard Rock Casino games!",
"revenue": 0.45,
"image": "https://cdn.adgem.com/campaigns/12119/campaign-offerwall-creatives/icons/202106252106.jpg",
"geo": [
"DE",
"FR",
"FI",
"DK",
"CZ",
"GB",
"CH",
"SE",
"ES",
"PT",
"NO",
"NL",
"HU",
"IT",
"GR"
],
"masterID": "adGem12119",
"devices": [
"ipad",
"iphone"
],
"link": "https://api.adgem.com/v1/click?all=1&appid=4746&cid=12119&playerid={playerid}",
"reward": "nothing",
"source": "adgem",
"isPromoted": true,
"priority": 1,
"isDisabled": false,
"forceType": "null"
}
}
This is the data structure:
const res = {
appID: appID,
cvr: cvr ,
name: data[1].Offer.name,
anchor: data[1].Offer.name,
short_desc: data[1].Offer.short_description,
long_desc: data[1].Offer.description,
revenue: data[1].Offer.payout_usd,
image: data[1].Offer.icon,
geo: Object.keys(data[1].Country.include),
masterID: "adGem" + data[1].Offer.campaign_id,
devices: [...new Set(data[1].Device.include)],
link: data[1].Offer.tracking_url,
reward: "nothing",
source: "adgem",
isPromoted: true,
priority: 1,
isDisabled: false,
forceType: "null",
};
This is the nested loop i am using:
for (let i = 0; i < offersFast.length; i++) {
for (let j = 0; j < offersFast[i].geo.length; j++) {
for (let k = 0; k < offersFast[i].devices.length; k++) {
const arrayName = offersFast[i].geo[j] + '_' + offersFast[i].devices[k]
tempArray[arrayName] = offersFast[i] // this is defined, just not added in this question.
}
}
}
Please try with below code.
let tempArray = {}
for (let i = 0; i < offersFast.length; i++) {
for (let j = 0; j < offersFast[i].geo.length; j++) {
for (let k = 0; k < offersFast[i].devices.length; k++) {
const arrayName = offersFast[i].geo[j] + '_' + offersFast[i].devices[k]
if (!Array.isArray(tempArray[arrayName]))
tempArray[arrayName] = new Array()
tempArray[arrayName].push(offersFast[i]) // this is defined, just not added in this question.
}
}
}

How to replace letters in string to dashes but not spaces

I am creating hangman and with this code I replace the content in string with dashes, but some strings are two words -- "hello world" -- which the output is - - - - - - - - - - - 11 characters instead of ten. How do I avoid replacing the space?
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++){
replaceWithDash[i] = "_";
}
console.log(randomPick);
console.log(replaceWithDash);
}
beginGame();
While you're looping over your letters, you'll want to check whether or not the target letter is a space or not. If it's not a space, replace it with a dash. If it is a space, however, you should replace it with a space instead.
Note that considering you're making use of the second array replaceWithDash rather than simply replacing the letters, you'll need to explicitly state that the letter in the new array should contain a space, rather than simply only running the logic when there is not a space. As such, the else is required in the following (or else you'd end up with undefined indexes):
for (i = 0; i < randomPick.length; i++) {
if (randomPick[i] !== " ") {
replaceWithDash[i] = "_";
}
else {
replaceWithDash[i] = " ";
}
}
This can be seen in the following:
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"
];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++) {
if (randomPick[i] !== " ") {
replaceWithDash[i] = "_";
}
else {
replaceWithDash[i] = " ";
}
}
console.log(randomPick);
console.log(replaceWithDash);
}
beginGame();
Hope this helps! :)
To answer your question, basically you need to check if the value you are inserting into the array is a space or not. If you want to do something different when it is a space, you can add an else statement to do so. Here you will just iterate over that element of the array and then use filter_array to clean it up.
var stateNames = ["alabama", "alaska", "arizona", "california",
"colorado", "connecticut", "delaware", "florida", "georgia",
"hawaii",
"idaho", "illinois", "indiana", "iowa", "kansas", "kentucky",
"louisiana", "maine", "maryland", "massachusetts", "michigan",
"minnesota", "mississippi", "missouri", "montana", "nebraska",
"nevada", "new hampshire", "new jersey", "new mexico", "new york",
"north carolina", "north dakota", "ohio", "oklahoma", "oregon",
"pennsylvania", "rhode island", "south carolina", "south dakota",
"tennessee", "texas", "utah", "vermont", "virgina", "washington",
"west virgina", "wisconsin", "wyoming"];
function beginGame() {
var randomPick = stateNames[Math.floor(Math.random() *
stateNames.length)];
var replaceWithDash = [];
for (i = 0; i < randomPick.length; i++){
if(randomPick.charAt(i-1) != " "){
replaceWithDash[i] = "_";
}
}
console.log(randomPick);
console.log(filter_array(replaceWithDash));
}
beginGame();
function filter_array(test_array) {
var index = -1,
arr_length = test_array ? test_array.length : 0,
resIndex = -1,
result = [];
while (++index < arr_length) {
var value = test_array[index];
if (value) {
result[++resIndex] = value;
}
}
return result;
}

Edit JSON data to Firebase format

I have json data in one format and need to edit to a format supported by Firebase. I have created a javascript application with function to try to edit the data format but doesnt seem to work. It is a large amount of data but below is a sample.
app.js application
var fs = require('fs');
//read data from file
var readData = fs.readFileSync('readMe.json','utf8');
var sample = JSON.parse(readData);
var newData =addFirebaseKey(sample);
// output datda to output.json
fs.writeFileSync('output.json',JSON.stringify(newData),'utf8');
function addFirebaseKey(contacts){
var fireContacts="";
for(var i=0;i<contacts.length;i++){
var tempObj=contacts[i];
//tel number is also the firebase key
var fireKey =tempObj.tel;
fireContacts=fireContacts+fireKey+tempObj;
}
return fireContacts;
}
readMe.json file
[
{
"contactName": "Office of the President",
"description": "office of president",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "123456",
"country": "Zambia"
},
{
"contactName": "State House",
"description": "State president, Ministry of",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "444900",
"country": "Zambia"
},
{
"contactName": "National Strategy Office",
"description": "national strategy",
"fax": "-",
"location": "Gaborone",
"postalAddress": "-",
"tel": "222222",
"country": "Zambia"
}
]
output.json file
"123456[object Object]444900[object Object]222222[object Object]"
This is the format that is required for Firebase
{
"contactDetail" : {
"Zambia" : {
"123456" : {
"contactName" : "Shocks & Exhaust Fitment Centre",
"description" : "motor vehicle exhaust systems",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "NA",
"tel" : "123456"
},
"888555" : {
"contactName" : "K Media",
"description" : "internet marketing",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "P O Box 26249, Gaborone",
"tel" : "888555"
},
"555544" : {
"contactName" : "Shocks & Exhaust Fitment Centre",
"description" : "secretarial services",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "NA",
"tel" : "555544"
}
}
}
}
To convert the data format:
let input = [
{
"contactName": "Office of the President",
"description": "office of president",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "123456",
"country": "Zambia"
},
{
"contactName": "State House",
"description": "State president, Ministry of",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "444900",
"country": "Zambia"
},
{
"contactName": "National Strategy Office",
"description": "national strategy",
"fax": "-",
"location": "Gaborone",
"postalAddress": "-",
"tel": "222222",
"country": "Zambia"
}
];
let output = {};
input.forEach((row) => {
if (!output[row.country]) output[row.country] = {};
output[row.country][row.tel] = row;
})
console.log(output);
After that you'll need to write it to Firebase or to a file.

JavaScript! Creating a Guess the word Game

Here's code :
let ccdisplay = document.querySelector('.crrDisplay');
let incdisplay = document.querySelector('.incDisplay');
let guess = document.querySelector('#character');
let textForm = document.querySelector('.textForm');
var commonWords = [
"the", "of", "and", "a", "to", "in", "is", "you", "that", "it",
"he", "was", "for", "on", "are", "as", "with", "his", "they","I", "at",
"be","this", "have", "from", "or", "one", "had", "by", "word", "but","not",
"what", "all", "were", "we", "when", "your", "can", "said", "there",
"use", "an", "each", "which", "she", "do", "how", "their", "if",
"will","up", "other", "about", "out", "many", "then", "them",
"these", "so","some", "her", "would", "make", "like", "him", "into", "time", "has",
"look", "two", "more", "write", "go", "see", "number", "no", "way",
"could", "people", "my", "than", "first", "water", "been", "call",
"who", "oil", "its", "now", "find", "long", "down", "day", "did",
"get", "come", "made", "may", "part"];
// Grabbing Random Word
var chooseRandomWord = function(array) {
return array[Math.floor(Math.random() * array.length)];
}
var chosenWord = chooseRandomWord(commonWords);
console.log(chosenWord)
// Function that submits the values
textForm.addEventListener('submit', function(event) {
var counter = 10;
var triedCharacters = [];
var correctCharacters = [];
event.preventDefault();
guess = character.value
for (i = 0; i < chosenWord.length; i++) {
chosenWord[i]
for (z = 0; z < guess.length; z++) {
if (guess[z] === chosenWord[i]) {
correctCharacters.push(guess[z])
console.log("correct " + correctCharacters)
}
else {
triedCharacters.push(guess[z])
console.log("incorrect " + triedCharacters)
}
};
}
})
Hey, I'm trying to create a game that guesses the random word and put the correct ones in one array and the incorrect characters in another array the correct array works but the incorrect else isn't working and pushing in every character.
There should be only one loop. You should also loop trough shorter word but a hint with word length would be nice...
let display = document.querySelector('.display');
let guessQuerySelector = document.querySelector('#character');
let textForm = document.querySelector('.textForm');
var commonWords = [
"the", "of", "and", "a", "to", "in", "is", "you", "that", "it", "he",
"was", "for", "on", "are", "as", "with", "his", "they", "I", "at", "be",
"this", "have", "from", "or", "one", "had", "by", "word", "but", "not",
"what", "all", "were", "we", "when", "your", "can", "said", "there",
"use", "an", "each", "which", "she", "do", "how", "their", "if", "will",
"up", "other", "about", "out", "many", "then", "them", "these", "so",
"some", "her", "would", "make", "like", "him", "into", "time", "has",
"look", "two", "more", "write", "go", "see", "number", "no", "way",
"could", "people", "my", "than", "first", "water", "been", "call",
"who", "oil", "its", "now", "find", "long", "down", "day", "did", "get",
"come", "made", "may", "part"
];
// Grabbing Random Word
var getRandomWord = function(array) {
return array[Math.floor(Math.random() * array.length)];
}
var randomWord = getRandomWord(commonWords);
console.log('randomWord', randomWord);
// Function that submits the values
textForm.addEventListener('submit', function(event) {
event.preventDefault();
var counter = 10;
var triedCharacters = [];
var correctCharacters = [];
var guessWord = guessQuerySelector.value;
var shorterWordlength = randomWord.length > guessWord.length ? guessWord.length : randomWord.length;
console.log('guessWord', guessWord);
for (i = 0; i < shorterWordlength; i++) {
if (guessWord[i] === randomWord[i]) {
correctCharacters.push(guessWord[i])
console.log("correct " + correctCharacters)
} else {
triedCharacters.push(guessWord[i])
console.log("incorrect " + triedCharacters)
}
}
randomWord = getRandomWord(commonWords);
console.log('randomWord', randomWord);
})

Javascript regular expression to remove domain extention

I would like a regex that can remove the domain extension from a string e.g. The string is from a text field so the user may or may not include http://www.
var fqdn = "http://www.mydomainname.com";
var name = regex_function(fqdn);
// name === "mydomainname"
There are 2 main ways to do this: with regular expressions and with using the DOM.
function regex_function(fqdn) {
var a = document.createElement('a');
a.href = fqdn;
return a.hostname || undefined;
}
There's no reliable way to remove domain extensions like .com, but why would you do that anyway?
This function does remove a few extensions, but please DO NOT use this, I just added it here to show you how much work and unnecessary code is required to even get close to removing a small portion of these extensions:
function removeExt(str){
var a = document.createElement('a');
a.href = str;
var hostName = a.hostname;
var domainExtensions = [
"gov", "org", "co", "com", "in", "info", "net", "uk", "af", "am", "ar", "au", "as", "az", "be", "bg", "bn", "bo", "bs", "ca", "cs", "cy", "da", "de", "dv", "el", "en", "es", "et", "eu", "fa", "fi", "fo", "fr", "gd", "gl", "gn", "gu", "he", "hi", "hr", "hu", "hy", "id", "is", "it", "jp", "ka", "kk", "km", "kn", "ko", "ks", "la", "lo", "lt", "lv", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my", "nb", "ne", "nl", "or", "pa", "pl", "pt", "rm", "ro", "ru", "sa", "sb", "sd", "si", "sk", "sl", "so", "sq", "sr", "sv", "sw", "ta", "te", "tg", "th", "tk", "tn", "tr", "ts", "tt", "uk", "ur", "uz", "vi", "xh", "yi", "zh", "zu"
];
var regex = new RegExp("\.?(\."+domainExtensions.join('|')+")+$");
return hostName.replace(regex,'');
}
Not so elegant, but it is working, in most regular cases- it seems:
function strip(fqdn) {
fqdn=fqdn.replace(/http:\/\/www./,'');
var i = fqdn.lastIndexOf('.');
var n=fqdn.substr(i,fqdn.length-1);
fqdn=fqdn.replace(n,'');
dot=fqdn.lastIndexOf('.');
if(dot!=-1) {
var n2=fqdn.substr(dot,fqdn.length-1);
fqdn=fqdn.replace(n2,'');
}
return fqdn;
}
Better one:
function strip_dom(fqdn) {
pattern=/\.+[0-9A-Za-z]+\./;
fqdn=fqdn.match(pattern);
fqdn=fqdn.join(fqdn,'');
fqdn=fqdn.replace(/\./g,'');
return fqdn;
}
Not working for subdomains (separated by dot), but with few tweaks...

Categories