How to replace letters in string to dashes but not spaces - javascript

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;
}

Related

Nested Object array values

I am utilizing jquery to loop thru 'searchResults' and looping thru 'SearchResult' and then looping again into 'SearchResultItems' to begin appending values. I then locate 'LocationDetails' and loop thru the nested values of State to display states for each 'DisplayTitle'.
If that description isn't well written, here is the code.
searchResults = [{
"SearchResult": {
"SearchResultItems": [{
"MatchedObjectDescriptor": {
"URI":"http://...",
"DisplayTitle": "Boss Person",
"LocationDetails": [{
"State": "California",
"CityName": "San Francisco County, California",
},{
"State": "Colorado",
"LocationName": "Denver, Colorado",
},{
"State": "California",
"CityName": "Los Angeles, California",
}]
}
},{
"MatchedObjectDescriptor": {
"URI":"http://...",
"DisplayTitle": "Assistant",
"LocationDetails": [{
"State": "Colorado",
"CityName": "Denver, Colorado",
},{
"State": "Colorado",
"LocationName": "Denver, Colorado",
},{
"State": "California",
"CityName": "Sacramento, California",
}]
}
},
]
}
}];
My current attempt at navigating the array of objects.
$.each(searchResults, function(key,value){
$.each(value.SearchResult.SearchResultItems,function(key,value){
var items = value.MatchedObjectDescriptor,
title = items.DisplayTitle;
$.each(items.LocationDetails, function(key,value){
var states = value.State;
$(".content").append("<ul><li>'" + title + "'<ul><li>'" + states + "'</li></ul></li></ul>");
});
});
});
See my work here so far with the wrong output: https://jsfiddle.net/arkjoseph/esvgcos7/15/
I am looking for this output filtering duplicate states and not having a different title for each state that is available in the object.
Boss person
California
Colorado
Assistant
Colorado
California
This gives you expected output.
searchResults = [{
"SearchResult": {
"SearchResultItems": [{
"MatchedObjectDescriptor": {
"URI": "http://...",
"DisplayTitle": "Boss Person",
"LocationDetails": [{
"State": "California",
"CityName": "San Francisco County, California",
}, {
"State": "Colorado",
"LocationName": "Denver, Colorado",
}, {
"State": "California",
"CityName": "Los Angeles, California",
}]
}
}, {
"MatchedObjectDescriptor": {
"URI": "http://...",
"DisplayTitle": "Assistant",
"LocationDetails": [{
"State": "Colorado",
"CityName": "Denver, Colorado",
}, {
"State": "Colorado",
"LocationName": "Denver, Colorado",
}, {
"State": "California",
"CityName": "Sacramento, California",
}]
}
}, ]
}
}];
var states = "";
$.each(searchResults, function(key, value) {
$.each(value.SearchResult.SearchResultItems, function(key, value) {
var items = value.MatchedObjectDescriptor,
title = items.DisplayTitle;
var s = [];
var li = "";
$.each(items.LocationDetails, function(key, value) {
var states = value.State;
if (!s.includes(states)) {
s.push(states);
li += ("<li>" + states + "</li>")
}
});
$(".content").append("<ul><li>" + title + "<ul>" + li + "</ul></li></ul>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="content"></div>
actual json endpoint: <a target="_blank" href="https://pastebin.com/embed_js/dRfMedYb">Here</a>
A working version of your code is as follows. This is just one example of how to do it, but using Set in ES6 (if you have an environment where it's permitted or are using a transpiler like Babel) might be desirable. Either way, this just appends to an array and joins on an empty string at the end to create your nodes. Using jQuery to build your elements also will likely be more scalable down the road, but for a small app the following works.
searchResults = [{
"SearchResult": {
"SearchResultItems": [{
"MatchedObjectDescriptor": {
"URI":"http://...",
"DisplayTitle": "Boss Person",
"LocationDetails": [{
"State": "California",
"CityName": "San Francisco County, California",
},{
"State": "Colorado",
"LocationName": "Denver, Colorado",
},{
"State": "California",
"CityName": "Los Angeles, California",
}]
}
},{
"MatchedObjectDescriptor": {
"URI":"http://...",
"DisplayTitle": "Assistant",
"LocationDetails": [{
"State": "Colorado",
"CityName": "Denver, Colorado",
},{
"State": "Colorado",
"LocationName": "Denver, Colorado",
},{
"State": "California",
"CityName": "Sacramento, California",
}]
}
},
]
}
}];
var states = [];
var output = [];
$.each(searchResults, function(key,value){
output.push("<ul>")
$.each(value.SearchResult.SearchResultItems,function(key,value){
var items = value.MatchedObjectDescriptor,
title = items.DisplayTitle;
output.push("<li>" + title + "</li>")
output.push("<ul>")
$.each(items.LocationDetails, function(key,value){
if (states.filter(s => s == value.State).length) return;
states.push(value.State)
output.push("<li>" + value.State + "</li>")
});
states = []
output.push("</ul>")
});
output.push('</ul>')
});
$(".content").append(output.join(''));

Salesforce Dependent picklist State and Country

I have got a solution for Salesforce Dependent Picklist values for Salesforce Site. As the Dependency is not publicly available for site I have found a solution using javascript and the country and state list are as per published by Salesforce on Feb'16 Edition. The code snippet is added below.
<!--- Include required libraries --->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" />
<script src="/soap/ajax/36.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/36.0/apex.js" type="text/javascript"></script>
<script src="../static/102010/js/picklist.js"></script>
<script type="text/javascript">
var country_arr = new Array("American Samoa", "Anguilla", "Antigua and Barbuda", "Argentina", "Aruba", "Australia", "Austria", "Bahamas", "Bangladesh", "Barbados", "Belgium", "Belize", "Bermuda", "Bolivia", "Brazil", "Brunei Darussalam", "Cambodia", "Canada", "Cayman Islands", "Chile", "China", "Colombia", "Cook Islands", "Costa Rica", "Cyprus", "Denmark", "Dominica", "Dominican Republic", "Ecuador", "El Salvador", "Faroe Islands", "Finland", "France", "French Guiana", "French Polynesia", "Germany", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guyana", "Haiti", "Honduras", "Hong Kong", "India", "Indonesia", "Ireland", "Italy", "Jamaica", "Japan", "Laos", "Liechtenstein", "Macao", "Malaysia", "Maldives", "Martinique", "Mauritania", "Mexico", "Micronesia, Federated States Of", "Monaco", "Montserrat", "Myanmar", "Nepal", "Netherlands", "Norway", "Nepal", "New Zealand", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Portugal", "Paraguay", "Reunion", "Russian Federation", "Solomon Islands", "Sweden", "Suriname", "El Salvador", "Swaziland", "Turks and Caicos Islands", "Thailand", "Timor-Leste", "Trinidad and Tobago", "Taiwan", "United Kingdom", "United States", "Uruguay", "Saint Vincent and the Grenadines", "Venezuela", "Virgin Islands (British)", "Vietnam", "Vanuatu", "Samoa", "South Africa");
// States
var s_a = new Array();
s_a[0]="";
s_a[1]="";
s_a[2]="";
s_a[3]="";
s_a[4]="BUENOS AIRES|CATAMARCA|CHACO|Chubut|CORDOBA|CORRIENTES|ENTRE RIOS|FORMOSA|JUJUY|LA PAMPA|LA RIOJA|MENDOZA|MISIONES|NEUQUEN|RIO NEGRO|SALTA|SAN JUAN|SAN LUIS|SANTA CRUZ|SANTA FE|SANTIAGO DEL ESTERO|TIERRA DEL FUEGO|TUCUMAN";
s_a[5]="";
s_a[6]="AUSTRALIAN CAPITAL TERRITORY|NEW SOUTH WALES|NORTHERN TERRITORY|QUEENSLAND|SOUTH AUSTRALIA|TASMANIA|VICTORIA|WESTERN AUSTRALIA";
s_a[7]="Burgenland|Salzburg|Vienna|Vorarlberg";
s_a[8]="";
s_a[9]="";
s_a[10]="";
s_a[11]="ANTWERP|FLEMISH BRABANT|HAINAUT|LIMBURG|LUXEMBOURG|NAMUR|WALLOON BRABANT";
s_a[12]="";
s_a[13]="";
s_a[14]="";
s_a[15]="ACRE|ALAGOAS|AMAPA|AMAZONAS|BAHIA|CEARA|DISTRITO FEDERAL|ESPIRITO SANTO|GOIAS|MARANHAO|MATO GROSSO|MATO GROSSO DO SUL|MINAS GERAIS|PARA|PARAIBA|PARANA|PERNAMBUCO|PIAUI|RIO DE JANEIRO|RIO GRANDE DO NORTE|RIO GRANDE DO SUL|RONDONIA|RORAIMA|SANTA CATARINA|SAO PAULO|SERGIPE|TOCANTINS";
s_a[16]="";
s_a[17]="";
s_a[18]="ALBERTA|BRITISH COLUMBIA|MANITOBA|NEW BRUNSWICK|NEWFOUNDLAND|NORTHWEST TERRITORIES|NOVA SCOTIA|NUNAVUT|ONTARIO|PRINCE EDWARD ISLAND|QUEBEC|SASKATCHEWAN|YUKON TERRITORY";
s_a[19]="";
s_a[20]="AISEN|ANTOFAGASTA|VALPARAISO";
s_a[21]="Anhui|Beijing|Chongqing|Fujian|Gansu|Guangdong|Guizhou|Hainan|Hebei|Heilongjiang|Henan|Hubei|Hunan|Jiangsu|Jiangxi|Jilin|Liaoning|Qinghai|Shaanxi|Shandong|Shanghai|Shanxi|Sichuan|Tianjin|Xizang|Yunnan|Zhejiang";
s_a[22]="";
s_a[23]="";
s_a[24]="";
s_a[25]="";
s_a[26]="";
s_a[27]="";
s_a[28]="";
s_a[29]="";
s_a[30]="";
s_a[31]="";
s_a[32]="AHVENANMAA";
s_a[33]="";
s_a[34]="";
s_a[35]="";
s_a[36]="";
s_a[37]="";
s_a[38]="";
s_a[39]="";
s_a[40]="";
s_a[41]="";
s_a[42]="";
s_a[43]="";
s_a[44]="";
s_a[45]="";
s_a[46]="Andhra Pradesh|Arunachal Pradesh|Assam|BIHAR|Chandigarh|Chhattisgarh|Delhi|Goa|Gujarat|Haryana|Himachal Pradesh|Jharkhand|Karnataka|Kerala|Lakshadweep|Madhya Pradesh|Maharashtra|Manipur|Meghalaya|Mizoram|Nagaland|ORISSA|Puducherry|Punjab|Rajasthan|Sikkim|Tamil Nadu|Tripura|Uttar Pradesh|Uttarakhand|West Bengal";
s_a[47]="";
s_a[48]="";
s_a[49]="AGRIGENTO|ALESSANDRIA|ANCONA|AOSTA|AREZZO|ASCOLI PICENO|ASTI|AVELLINO|BARI|BELLUNO|BENEVENTO|BERGAMO|BIELLA|BOLOGNA|BOLZANO|BRESCIA|BRINDISI|CAGLIARI|CALTANISSETTA|CAMPOBASSO|CARBONIA-IGLESIAS|CASERTA|CATANIA|CATANZARO|CHIETI|COMO|COSENZA|CREMONA|CROTONE|CUNEO|ENNA|FERRARA|FOGGIA|FROSINONE|GORIZIA|GROSSETO|IMPERIA|ISERNIA|LA SPEZIA|LATINA|LECCE|LECCO|LIVORNO|LODI|LUCCA|MACERATA|MATERA|MEDIO CAMPIDANO|MESSINA|MODENA|NOVARA|NUORO|OGLIASTRA|OLBIA-TEMPIO|ORISTANO|PALERMO|PARMA|PAVIA|PERUGIA|PESARO E URBINO|PESCARA|PIACENZA|PISA|PISTOIA|PORDENONE|POTENZA|PRATO|RAGUSA|RAVENNA|RIETI|RIMINI|ROVIGO|SALERNO|SASSARI|SAVONA|SIENA|SONDRIO|TARANTO|TERAMO|TERNI|TRAPANI|TRENTO|TREVISO|TRIESTE|UDINE|VARESE|VERBANO-CUSIO-OSSOLA|VERCELLI|VERONA|VIBO VALENTIA|VICENZA|VITERBO";
s_a[50]="";
s_a[51]="AICHI|AKITA|AOMORI|CHIBA|EHIME|FUKUI|FUKUOKA|FUKUSHIMA|GIFU|HIROSHIMA|HOKKAIDO|HYOGO|Ibaraki|ISHIKAWA|IWATE|KAGAWA|KAGOSHIMA|KANAGAWA|KOCHI|KUMAMOTO|KYOTO|MIE|MIYAGI|MIYAZAKI|NAGANO|NAGASAKI|NARA|NIIGATA|OITA|OKAYAMA|OKINAWA|OSAKA|SAGA|SAITAMA|SHIGA|SHIMANE|SHIZUOKA|TOCHIGI|TOKUSHIMA|TOKYO|TOTTORI|TOYAMA|Wakayama|YAMAGATA|YAMAGUCHI|YAMANASHI";
s_a[52]="";
s_a[53]="";
s_a[54]="";
s_a[55]="";
s_a[56]="";
s_a[57]="";
s_a[58]="";
s_a[59]="AGUASCALIENTES|BAJA CALIFORNIA|BAJA CALIFORNIA SUR|CAMPECHE|CHIAPAS|CHIHUAHUA|COAHUILA|COLIMA|DISTRITO FEDERAL|DURANGO|GUANAJUATO|GUERRERO|HIDALGO|JALISCO|MICHOACAN|MORELOS|NAYARIT|NUEVO LEON|OAXACA|PUEBLA|QUERETARO|QUINTANA ROO|SAN LUIS POTOSI|SINALOA|SONORA|TABASCO|TAMAULIPAS|TLAXCALA|VERACRUZ|YUCATAN|ZACATECAS";
s_a[60]="";
s_a[61]="";
s_a[62]="";
s_a[63]="";
s_a[64]="";
s_a[65]="DRENTHE|FLEVOLAND|FRIESLAND|GELDERLAND|GRONINGEN|LIMBURG|NOORD-BRABANT|NOORD-HOLLAND|OVERIJSSEL|UTRECHT|ZEELAND|ZUID-HOLLAND";
s_a[66]="";
s_a[67]="";
s_a[68]="";
s_a[69]="";
s_a[70]="";
s_a[71]="";
s_a[72]="";
s_a[73]="";
s_a[74]="";
s_a[75]="";
s_a[76]="";
s_a[77]="";
s_a[78]="";
s_a[79]="";
s_a[80]="";
s_a[81]="BLEKINGE|DALARNA|GAVLEBORG|GOTLAND|HALLAND|JAMTLAND|JONKOPING|KALMAR|KRONOBERG|NORRBOTTEN|OREBRO|OSTERGOTLAND|SKANE|SODERMANLAND|STOCKHOLM|UPPSALA|VARMLAND|VASTERBOTTEN|VASTERNORRLAND|VASTMANLAND|VASTRA GOTALAND";
s_a[82]="";
s_a[83]="";
s_a[84]="";
s_a[85]="";
s_a[86]="";
s_a[87]="";
s_a[88]="";
s_a[89]="";
s_a[90]="";
s_a[91]="Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|District of Columbia|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|Puerto Rico|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virgin Islands|Virginia|Washington|West Virginia|Wisconsin|Wyoming";
s_a[92]="";
s_a[93]="";
s_a[94]="";
s_a[95]="";
s_a[96]="";
s_a[97]="";
s_a[98]="";
s_a[99]="";
function populateStates( countryElementId, stateElementId ){
var selectedCountryIndex = document.getElementById( countryElementId ).selectedIndex;
//var stateElement = document.getElementById( stateElementId );
var stateElement = $("#page\\:MainForm\\:MainPageBlock\\:stateID");
stateElement.length=0; // Fixed by Julian Woods
stateElement.options[0] = new Option('Select State','');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i=0; i<state_arr.length; i++) {
stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
}
}
function createCountries(){
var country_sl="{!OpwrapAccBillCountry}";
var sel=$.inArray(country_sl, country_arr);
console.log("sel="+sel);
var countryElement = $("#countryID");
countryElement.find('option').remove().end().append('<option value="">--Select--</option>');
var part1='<option value=\"';
var part2='\">';
var part3='</option>';
for (var i=0; i<country_arr.length; i++) {
//countryElement.options[countryElement.length] = new Option(country_arr[i],country_arr[i]);
//console.log(country_arr[i]);
countryElement.append(part1+country_arr[i]+part2+country_arr[i]+part3);
}
countryElement.val(country_sl);
loadDependentPicklist();
var stateElement = $("#stateID");
var state_sl="{!OpwrapAccBillState}";
stateElement.val(state_sl);
}
function loadDependentPicklist(){
var countryElementId = $("#countryID");
var countryElement_hid = $("#page\\:MainForm\\:MainPageBlock\\:country_hid");
countryElement_hid.val(countryElementId.val());
var stateElement = $("#stateID");
stateElement.find('option').remove().end().append('<option value="">--Select--</option>');
var selectedCountryIndex=countryElementId.prop('selectedIndex');
var state_arr = s_a[selectedCountryIndex].split("|");
var part1='<option value=\"';
var part2='\">';
var part3='</option>';
for (var i=0; i<state_arr.length; i++) {
//stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
console.log("state_arr[i]="+state_arr[i]);
stateElement.append(part1+state_arr[i]+part2+state_arr[i]+part3);
}
}
function stateSel(){
var stateElement = $("#stateID");
var stateElement_hid=$("#page\\:MainForm\\:MainPageBlock\\:state_hid");
stateElement_hid.val(stateElement.val());
}
</script>
<script type="text/javascript">
$( document ).ready(function() {
console.log( "ready!" );
createCountries();
});
</script>

Deeper understanding of Promises

In my controller, I have a branches array in which I need to append location object containing lat long to each item of it i.e.
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009009",
"MICR CODE": "400034002",
"BRANCH": "MUMBAI",
"ADDRESS": "FRENCH BANK BLDG.,62, HOMJI STREET, MUMBAI - 400 001",
"CONTACT": "0",
"CITY": "MUMBAI",
"DISTRICT": "MUMBAI",
"STATE": "MAHARASHTRA",
"ZIPCODE": "400 001",
"location": {
lat: ,
long:
}
},
I am doing so by iterating the branches vi angular forEach and calling the getLatLong function on each item inside forEach loop.
However, the control/execution of the function is such that it return deferred.promise before I have got any results from service call. Ideally I want to have the location object from google maps API and then when it resolves I want the results back to controller function getLatLong and return that location object which in turn be assigned to item.location in forEach loop.
My controller
module.exports = function(AppFactory, $q){
'use strict';
let ctrl = this;
ctrl.showList = true;
ctrl.branches = [
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009008",
"MICR CODE": "700034002",
"BRANCH": "KOLKATA",
"ADDRESS": "UNIT NO. 301, OFFICE NO. 2, 3RD FLOOR, AVANI SIGNATURE,91A/1, PARK STREET,KOLKATA :- 700016",
"CONTACT": "0",
"CITY": "KOLKATA",
"DISTRICT": "KOLKATA",
"STATE": "WEST BENGAL",
"ZIPCODE": "700016"
},
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009009",
"MICR CODE": "400034002",
"BRANCH": "MUMBAI",
"ADDRESS": "FRENCH BANK BLDG.,62, HOMJI STREET, MUMBAI - 400 001",
"CONTACT": "0",
"CITY": "MUMBAI",
"DISTRICT": "MUMBAI",
"STATE": "MAHARASHTRA",
"ZIPCODE": "400 001"
},
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009065",
"MICR CODE": "110034002",
"BRANCH": "DELHI",
"ADDRESS": "1ST FLOOR EAST TOWER (SOOD TOWER), 25, BARAKHAMBA ROAD,NEW DELHI :- 110001",
"CONTACT": "0",
"CITY": "DELHI",
"DISTRICT": "DELHI",
"STATE": "DELHI",
"ZIPCODE": "110001"
},
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009067",
"MICR CODE": "560034002",
"BRANCH": "BANGALORE",
"ADDRESS": "3RD FL,LANDMARK,21/15,M.G.ROAD,BANGLORE-560 001",
"CONTACT": "0",
"CITY": "BANGALORE",
"DISTRICT": "BANGALORE",
"STATE": "KARNATAKA",
"ZIPCODE": "560 001"
},
{
"BANK": "B N P PARIBAS",
"IFSC": "BNPA0009069",
"MICR CODE": "411034002",
"BRANCH": "PUNE",
"ADDRESS": "5 & 6,GODREJ MILLENIUM PARK,9,KOREGAON ROAD,PUNE-411 001",
"CONTACT": "0",
"CITY": "PUNE",
"DISTRICT": "PUNE",
"STATE": "MAHARASHTRA",
"ZIPCODE": "411 001"
}
]
// console.log(ctrl.branches);
function getLatLong(addressOrZip){
let results;
let deferred = $q.defer();
AppFactory.getLatLong(addressOrZip).then(function(res){
console.log(res);
deferred.resolve(res);
// if(res.results.length > 0){
// results = res.results[0].geometry.location;
// }else{
// results = res.results;
// }
// return results;
}, function(error){
deferred.reject(res);
});
return deferred.promise;
}
ctrl.toggleViews = function(){
ctrl.showList = !ctrl.showList;
if(!ctrl.showList){
angular.forEach(ctrl.branches, function(item){
let location = getLatLong(item.ZIPCODE );
console.log(location);
// let location = getLatLong( item.ADDRESS || item.ZIPCODE );
// if(location){
// item.location = location;
// }
})
console.log("Logging branches with location object...");
console.log(ctrl.branches);
}
}
}
Then in my AppFactory
let getLatLong = function(location){
// let defferred = $q.defer();
return $http({
url: "https://maps.googleapis.com/maps/api/geocode/json?address="+ location +"&key=AIzaSyDGyOrnNj8rrRFR92m6BEMvR24JiYoHtMs"
}).then(function(response){
return response.data;
// defferred.resolve(response.data);
}, function(error){
return error;
// defferred.reject(error);
});
// return defferred.promise;
}
How can I get around this ?
getLatLong() returns a promise (which is what $http returns) so you need to use then() on that returned promise to access the response data
Change:
let location = getLatLong(item.ZIPCODE );
console.log(location);
To:
getLatLong(item.ZIPCODE ).then(function(data){
item.location = data;
console.log(item.location);
});
Will leave it up to you to validate that error is not returned to this then()

Javascript - JSON - Nesting and Grouping

I have the following JSON object that I need to un-nest, regroup and re-nest by the state. I understand that there must be some kind of for-loop and group by operation that needs to be performed.
[
{
"Date": "2000-01-01T08:00:00.000Z",
"Florida": "4626",
"New York": "210",
"Pennsylvania": "1500",
"Virginia": "9",
"West Virginia": "1400",
"Illinois": "12206",
"Indiana": "2098",
"Kansas": "34463",
"Kentucky": "3465",
"Michigan": "7907",
"Missouri": "94",
"Nebraska": "2957",
"North Dakota": "32719",
"Ohio": "6575",
"Oklahoma": "69976",
"South Dakota": "1170",
"Tennessee": "346",
"Alabama": "10457",
"Arkansas": "7154",
"Louisiana": "105425",
"Mississippi": "19844",
"New Mexico": "67198",
"Texas": "443397",
"Colorado": "18481",
"Montana": "15428",
"Utah": "15636",
"Wyoming": "60726",
"Alaska": "355199",
"Alaska South": "10590",
"Arizona": "59",
"California": "271132",
"Nevada": "621",
"": ""
},
{
"Date": "2001-01-01T08:00:00.000Z",
"Florida": "4426",
"New York": "166",
"Pennsylvania": "1620",
"Virginia": "11",
"West Virginia": "1226",
"Illinois": "10092",
"Indiana": "2022",
"Kansas": "33942",
"Kentucky": "2969",
"Michigan": "7375",
"Missouri": "91",
"Nebraska": "2922",
"North Dakota": "31691",
"Ohio": "6051",
"Oklahoma": "68531",
"South Dakota": "1255",
"Tennessee": "351",
"Alabama": "9334",
"Arkansas": "7592",
"Louisiana": "104610",
"Mississippi": "19528",
"New Mexico": "68001",
"Texas": "424297",
"Colorado": "16520",
"Montana": "15920",
"Utah": "15252",
"Wyoming": "57433",
"Alaska": "351411",
"Alaska South": "11500",
"Arizona": "59",
"California": "260663",
"Nevada": "572",
"": ""
},
{
"Date": "2002-01-01T08:00:00.000Z",
"Florida": "3634",
"New York": "164",
"Pennsylvania": "2324",
"Virginia": "25",
"West Virginia": "1456",
"Illinois": "11100",
"Indiana": "1962",
"Kansas": "33380",
"Kentucky": "2721",
"Michigan": "7218",
"Missouri": "95",
"Nebraska": "2782",
"North Dakota": "30803",
"Ohio": "5631",
"Oklahoma": "66421",
"South Dakota": "1214",
"Tennessee": "275",
"Alabama": "8636",
"Arkansas": "7252",
"Louisiana": "93321",
"Mississippi": "19371",
"New Mexico": "67562",
"Texas": "405776",
"Colorado": "20522",
"Montana": "16990",
"Utah": "13771",
"Wyoming": "54801",
"Alaska": "359382",
"Alaska South": "11303",
"Arizona": "63",
"California": "257898",
"Nevada": "553",
"": ""
}
]
I would like to process the above into the following format where state key is state name and production key is an array of dictionaries with years and production for that year.
[
{
"state": "California",
"production": [
{
"Date": "2000-01-01T08:00:00.000Z",
"production": 1000
},
{
"Date": "2001-01-01T08:00:00.000Z",
"production": 2000
}
]
},
{
"state": "New York",
"production": [
{
"Date": "2000-01-01T08:00:00.000Z",
"production": 4000
},
{
"Date": "2001-01-01T08:00:00.000Z",
"production": 5000
}
]
}
]
Please let me know what operations are needed to perform to achive the above format. Thank you!
Maybe this is working for you, with some iteration and an object as reference.
var data = [{ "Date": "2000-01-01T08:00:00.000Z", "Florida": "4626", "New York": "210", "Pennsylvania": "1500", "Virginia": "9", "West Virginia": "1400", "Illinois": "12206", "Indiana": "2098", "Kansas": "34463", "Kentucky": "3465", "Michigan": "7907", "Missouri": "94", "Nebraska": "2957", "North Dakota": "32719", "Ohio": "6575", "Oklahoma": "69976", "South Dakota": "1170", "Tennessee": "346", "Alabama": "10457", "Arkansas": "7154", "Louisiana": "105425", "Mississippi": "19844", "New Mexico": "67198", "Texas": "443397", "Colorado": "18481", "Montana": "15428", "Utah": "15636", "Wyoming": "60726", "Alaska": "355199", "Alaska South": "10590", "Arizona": "59", "California": "271132", "Nevada": "621", "": "" }, { "Date": "2001-01-01T08:00:00.000Z", "Florida": "4426", "New York": "166", "Pennsylvania": "1620", "Virginia": "11", "West Virginia": "1226", "Illinois": "10092", "Indiana": "2022", "Kansas": "33942", "Kentucky": "2969", "Michigan": "7375", "Missouri": "91", "Nebraska": "2922", "North Dakota": "31691", "Ohio": "6051", "Oklahoma": "68531", "South Dakota": "1255", "Tennessee": "351", "Alabama": "9334", "Arkansas": "7592", "Louisiana": "104610", "Mississippi": "19528", "New Mexico": "68001", "Texas": "424297", "Colorado": "16520", "Montana": "15920", "Utah": "15252", "Wyoming": "57433", "Alaska": "351411", "Alaska South": "11500", "Arizona": "59", "California": "260663", "Nevada": "572", "": "" }, { "Date": "2002-01-01T08:00:00.000Z", "Florida": "3634", "New York": "164", "Pennsylvania": "2324", "Virginia": "25", "West Virginia": "1456", "Illinois": "11100", "Indiana": "1962", "Kansas": "33380", "Kentucky": "2721", "Michigan": "7218", "Missouri": "95", "Nebraska": "2782", "North Dakota": "30803", "Ohio": "5631", "Oklahoma": "66421", "South Dakota": "1214", "Tennessee": "275", "Alabama": "8636", "Arkansas": "7252", "Louisiana": "93321", "Mississippi": "19371", "New Mexico": "67562", "Texas": "405776", "Colorado": "20522", "Montana": "16990", "Utah": "13771", "Wyoming": "54801", "Alaska": "359382", "Alaska South": "11303", "Arizona": "63", "California": "257898", "Nevada": "553", "": "" }],
grouped = [];
data.forEach(function (a) {
Object.keys(a).forEach(function (k) {
if (k !== 'Date') {
if (!this[k]) {
this[k] = { state: k, production: [] };
grouped.push(this[k]);
}
this[k].production.push({ Date: a.Date, production: a[k] });
}
}, this);
}, Object.create(null));
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

How to get domain name only using 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

Categories