How to remove extra characters from the end of email addresses - javascript
I'd like to remove extra characters from the end of email addresses, for example the "www" from xy#gmail.comwww
I created a function which gets the value from an input field and then I tried to use regular expression to check the email pattern, but it won't remove the additional characters from the end of the email address.
const txtContent = document.getElementById("txtContent");
function checkEmails() {
const temp = txtContent.value;
// Match email pattern
const regexp = /([A-Za-z0-9._-]+#[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+)/gi;
// Get the email by matching against the regexp
const emailsRaw = temp.match(regexp);
// Remove duplicate emails
const emails = [];
if (emailsRaw != null) {
emailsRaw.forEach(email => {
// Check if the email address is already included in the emails array
if (!emails.includes(email)) {
emails.push(email);
}
});
}
return emails;
}
console.log(checkEmails())
<textarea id="txtContent">aa#aaa.comwww</textarea>
// tlds from https://data.iana.org/TLD/tlds-alpha-by-domain.txt
const tlds = ['AAA', 'AARP', 'ABARTH', 'ABB', 'ABBOTT', 'ABBVIE', 'ABC', 'ABLE', 'ABOGADO', 'ABUDHABI', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACO', 'ACTOR', 'AD', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AETNA', 'AF', 'AFL', 'AFRICA', 'AG', 'AGAKHAN', 'AGENCY', 'AI', 'AIG', 'AIRBUS', 'AIRFORCE', 'AIRTEL', 'AKDN', 'AL', 'ALFAROMEO', 'ALIBABA', 'ALIPAY', 'ALLFINANZ', 'ALLSTATE', 'ALLY', 'ALSACE', 'ALSTOM', 'AM', 'AMAZON', 'AMERICANEXPRESS', 'AMERICANFAMILY', 'AMEX', 'AMFAM', 'AMICA', 'AMSTERDAM', 'ANALYTICS', 'ANDROID', 'ANQUAN', 'ANZ', 'AO', 'AOL', 'APARTMENTS', 'APP', 'APPLE', 'AQ', 'AQUARELLE', 'AR', 'ARAB', 'ARAMCO', 'ARCHI', 'ARMY', 'ARPA', 'ART', 'ARTE', 'AS', 'ASDA', 'ASIA', 'ASSOCIATES', 'AT', 'ATHLETA', 'ATTORNEY', 'AU', 'AUCTION', 'AUDI', 'AUDIBLE', 'AUDIO', 'AUSPOST', 'AUTHOR', 'AUTO', 'AUTOS', 'AVIANCA', 'AW', 'AWS', 'AX', 'AXA', 'AZ', 'AZURE', 'BA', 'BABY', 'BAIDU', 'BANAMEX', 'BANANAREPUBLIC', 'BAND', 'BANK', 'BAR', 'BARCELONA', 'BARCLAYCARD', 'BARCLAYS', 'BAREFOOT', 'BARGAINS', 'BASEBALL', 'BASKETBALL', 'BAUHAUS', 'BAYERN', 'BB', 'BBC', 'BBT', 'BBVA', 'BCG', 'BCN', 'BD', 'BE', 'BEATS', 'BEAUTY', 'BEER', 'BENTLEY', 'BERLIN', 'BEST', 'BESTBUY', 'BET', 'BF', 'BG', 'BH', 'BHARTI', 'BI', 'BIBLE', 'BID', 'BIKE', 'BING', 'BINGO', 'BIO', 'BIZ', 'BJ', 'BLACK', 'BLACKFRIDAY', 'BLOCKBUSTER', 'BLOG', 'BLOOMBERG', 'BLUE', 'BM', 'BMS', 'BMW', 'BN', 'BNPPARIBAS', 'BO', 'BOATS', 'BOEHRINGER', 'BOFA', 'BOM', 'BOND', 'BOO', 'BOOK', 'BOOKING', 'BOSCH', 'BOSTIK', 'BOSTON', 'BOT', 'BOUTIQUE', 'BOX', 'BR', 'BRADESCO', 'BRIDGESTONE', 'BROADWAY', 'BROKER', 'BROTHER', 'BRUSSELS', 'BS', 'BT', 'BUILD', 'BUILDERS', 'BUSINESS', 'BUY', 'BUZZ', 'BV', 'BW', 'BY', 'BZ', 'BZH', 'CA', 'CAB', 'CAFE', 'CAL', 'CALL', 'CALVINKLEIN', 'CAM', 'CAMERA', 'CAMP', 'CANON', 'CAPETOWN', 'CAPITAL', 'CAPITALONE', 'CAR', 'CARAVAN', 'CARDS', 'CARE', 'CAREER', 'CAREERS', 'CARS', 'CASA', 'CASE', 'CASH', 'CASINO', 'CAT', 'CATERING', 'CATHOLIC', 'CBA', 'CBN', 'CBRE', 'CBS', 'CC', 'CD', 'CENTER', 'CEO', 'CERN', 'CF', 'CFA', 'CFD', 'CG', 'CH', 'CHANEL', 'CHANNEL', 'CHARITY', 'CHASE', 'CHAT', 'CHEAP', 'CHINTAI', 'CHRISTMAS', 'CHROME', 'CHURCH', 'CI', 'CIPRIANI', 'CIRCLE', 'CISCO', 'CITADEL', 'CITI', 'CITIC', 'CITY', 'CITYEATS', 'CK', 'CL', 'CLAIMS', 'CLEANING', 'CLICK', 'CLINIC', 'CLINIQUE', 'CLOTHING', 'CLOUD', 'CLUB', 'CLUBMED', 'CM', 'CN', 'CO', 'COACH', 'CODES', 'COFFEE', 'COLLEGE', 'COLOGNE', 'COM', 'COMCAST', 'COMMBANK', 'COMMUNITY', 'COMPANY', 'COMPARE', 'COMPUTER', 'COMSEC', 'CONDOS', 'CONSTRUCTION', 'CONSULTING', 'CONTACT', 'CONTRACTORS', 'COOKING', 'COOKINGCHANNEL', 'COOL', 'COOP', 'CORSICA', 'COUNTRY', 'COUPON', 'COUPONS', 'COURSES', 'CPA', 'CR', 'CREDIT', 'CREDITCARD', 'CREDITUNION', 'CRICKET', 'CROWN', 'CRS', 'CRUISE', 'CRUISES', 'CU', 'CUISINELLA', 'CV', 'CW', 'CX', 'CY', 'CYMRU', 'CYOU', 'CZ', 'DABUR', 'DAD', 'DANCE', 'DATA', 'DATE', 'DATING', 'DATSUN', 'DAY', 'DCLK', 'DDS', 'DE', 'DEAL', 'DEALER', 'DEALS', 'DEGREE', 'DELIVERY', 'DELL', 'DELOITTE', 'DELTA', 'DEMOCRAT', 'DENTAL', 'DENTIST', 'DESI', 'DESIGN', 'DEV', 'DHL', 'DIAMONDS', 'DIET', 'DIGITAL', 'DIRECT', 'DIRECTORY', 'DISCOUNT', 'DISCOVER', 'DISH', 'DIY', 'DJ', 'DK', 'DM', 'DNP', 'DO', 'DOCS', 'DOCTOR', 'DOG', 'DOMAINS', 'DOT', 'DOWNLOAD', 'DRIVE', 'DTV', 'DUBAI', 'DUNLOP', 'DUPONT', 'DURBAN', 'DVAG', 'DVR', 'DZ', 'EARTH', 'EAT', 'EC', 'ECO', 'EDEKA', 'EDU', 'EDUCATION', 'EE', 'EG', 'EMAIL', 'EMERCK', 'ENERGY', 'ENGINEER', 'ENGINEERING', 'ENTERPRISES', 'EPSON', 'EQUIPMENT', 'ER', 'ERICSSON', 'ERNI', 'ES', 'ESQ', 'ESTATE', 'ET', 'ETISALAT', 'EU', 'EUROVISION', 'EUS', 'EVENTS', 'EXCHANGE', 'EXPERT', 'EXPOSED', 'EXPRESS', 'EXTRASPACE', 'FAGE', 'FAIL', 'FAIRWINDS', 'FAITH', 'FAMILY', 'FAN', 'FANS', 'FARM', 'FARMERS', 'FASHION', 'FAST', 'FEDEX', 'FEEDBACK', 'FERRARI', 'FERRERO', 'FI', 'FIAT', 'FIDELITY', 'FIDO', 'FILM', 'FINAL', 'FINANCE', 'FINANCIAL', 'FIRE', 'FIRESTONE', 'FIRMDALE', 'FISH', 'FISHING', 'FIT', 'FITNESS', 'FJ', 'FK', 'FLICKR', 'FLIGHTS', 'FLIR', 'FLORIST', 'FLOWERS', 'FLY', 'FM', 'FO', 'FOO', 'FOOD', 'FOODNETWORK', 'FOOTBALL', 'FORD', 'FOREX', 'FORSALE', 'FORUM', 'FOUNDATION', 'FOX', 'FR', 'FREE', 'FRESENIUS', 'FRL', 'FROGANS', 'FRONTDOOR', 'FRONTIER', 'FTR', 'FUJITSU', 'FUN', 'FUND', 'FURNITURE', 'FUTBOL', 'FYI', 'GA', 'GAL', 'GALLERY', 'GALLO', 'GALLUP', 'GAME', 'GAMES', 'GAP', 'GARDEN', 'GAY', 'GB', 'GBIZ', 'GD', 'GDN', 'GE', 'GEA', 'GENT', 'GENTING', 'GEORGE', 'GF', 'GG', 'GGEE', 'GH', 'GI', 'GIFT', 'GIFTS', 'GIVES', 'GIVING', 'GL', 'GLASS', 'GLE', 'GLOBAL', 'GLOBO', 'GM', 'GMAIL', 'GMBH', 'GMO', 'GMX', 'GN', 'GODADDY', 'GOLD', 'GOLDPOINT', 'GOLF', 'GOO', 'GOODYEAR', 'GOOG', 'GOOGLE', 'GOP', 'GOT', 'GOV', 'GP', 'GQ', 'GR', 'GRAINGER', 'GRAPHICS', 'GRATIS', 'GREEN', 'GRIPE', 'GROCERY', 'GROUP', 'GS', 'GT', 'GU', 'GUARDIAN', 'GUCCI', 'GUGE', 'GUIDE', 'GUITARS', 'GURU', 'GW', 'GY', 'HAIR', 'HAMBURG', 'HANGOUT', 'HAUS', 'HBO', 'HDFC', 'HDFCBANK', 'HEALTH', 'HEALTHCARE', 'HELP', 'HELSINKI', 'HERE', 'HERMES', 'HGTV', 'HIPHOP', 'HISAMITSU', 'HITACHI', 'HIV', 'HK', 'HKT', 'HM', 'HN', 'HOCKEY', 'HOLDINGS', 'HOLIDAY', 'HOMEDEPOT', 'HOMEGOODS', 'HOMES', 'HOMESENSE', 'HONDA', 'HORSE', 'HOSPITAL', 'HOST', 'HOSTING', 'HOT', 'HOTELES', 'HOTELS', 'HOTMAIL', 'HOUSE', 'HOW', 'HR', 'HSBC', 'HT', 'HU', 'HUGHES', 'HYATT', 'HYUNDAI', 'IBM', 'ICBC', 'ICE', 'ICU', 'ID', 'IE', 'IEEE', 'IFM', 'IKANO', 'IL', 'IM', 'IMAMAT', 'IMDB', 'IMMO', 'IMMOBILIEN', 'IN', 'INC', 'INDUSTRIES', 'INFINITI', 'INFO', 'ING', 'INK', 'INSTITUTE', 'INSURANCE', 'INSURE', 'INT', 'INTERNATIONAL', 'INTUIT', 'INVESTMENTS', 'IO', 'IPIRANGA', 'IQ', 'IR', 'IRISH', 'IS', 'ISMAILI', 'IST', 'ISTANBUL', 'IT', 'ITAU', 'ITV', 'JAGUAR', 'JAVA', 'JCB', 'JE', 'JEEP', 'JETZT', 'JEWELRY', 'JIO', 'JLL', 'JM', 'JMP', 'JNJ', 'JO', 'JOBS', 'JOBURG', 'JOT', 'JOY', 'JP', 'JPMORGAN', 'JPRS', 'JUEGOS', 'JUNIPER', 'KAUFEN', 'KDDI', 'KE', 'KERRYHOTELS', 'KERRYLOGISTICS', 'KERRYPROPERTIES', 'KFH', 'KG', 'KH', 'KI', 'KIA', 'KIDS', 'KIM', 'KINDER', 'KINDLE', 'KITCHEN', 'KIWI', 'KM', 'KN', 'KOELN', 'KOMATSU', 'KOSHER', 'KP', 'KPMG', 'KPN', 'KR', 'KRD', 'KRED', 'KUOKGROUP', 'KW', 'KY', 'KYOTO', 'KZ', 'LA', 'LACAIXA', 'LAMBORGHINI', 'LAMER', 'LANCASTER', 'LANCIA', 'LAND', 'LANDROVER', 'LANXESS', 'LASALLE', 'LAT', 'LATINO', 'LATROBE', 'LAW', 'LAWYER', 'LB', 'LC', 'LDS', 'LEASE', 'LECLERC', 'LEFRAK', 'LEGAL', 'LEGO', 'LEXUS', 'LGBT', 'LI', 'LIDL', 'LIFE', 'LIFEINSURANCE', 'LIFESTYLE', 'LIGHTING', 'LIKE', 'LILLY', 'LIMITED', 'LIMO', 'LINCOLN', 'LINDE', 'LINK', 'LIPSY', 'LIVE', 'LIVING', 'LK', 'LLC', 'LLP', 'LOAN', 'LOANS', 'LOCKER', 'LOCUS', 'LOL', 'LONDON', 'LOTTE', 'LOTTO', 'LOVE', 'LPL', 'LPLFINANCIAL', 'LR', 'LS', 'LT', 'LTD', 'LTDA', 'LU', 'LUNDBECK', 'LUXE', 'LUXURY', 'LV', 'LY', 'MA', 'MACYS', 'MADRID', 'MAIF', 'MAISON', 'MAKEUP', 'MAN', 'MANAGEMENT', 'MANGO', 'MAP', 'MARKET', 'MARKETING', 'MARKETS', 'MARRIOTT', 'MARSHALLS', 'MASERATI', 'MATTEL', 'MBA', 'MC', 'MCKINSEY', 'MD', 'ME', 'MED', 'MEDIA', 'MEET', 'MELBOURNE', 'MEME', 'MEMORIAL', 'MEN', 'MENU', 'MERCKMSD', 'MG', 'MH', 'MIAMI', 'MICROSOFT', 'MIL', 'MINI', 'MINT', 'MIT', 'MITSUBISHI', 'MK', 'ML', 'MLB', 'MLS', 'MM', 'MMA', 'MN', 'MO', 'MOBI', 'MOBILE', 'MODA', 'MOE', 'MOI', 'MOM', 'MONASH', 'MONEY', 'MONSTER', 'MORMON', 'MORTGAGE', 'MOSCOW', 'MOTO', 'MOTORCYCLES', 'MOV', 'MOVIE', 'MP', 'MQ', 'MR', 'MS', 'MSD', 'MT', 'MTN', 'MTR', 'MU', 'MUSEUM', 'MUSIC', 'MUTUAL', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NAB', 'NAGOYA', 'NAME', 'NATURA', 'NAVY', 'NBA', 'NC', 'NE', 'NEC', 'NET', 'NETBANK', 'NETFLIX', 'NETWORK', 'NEUSTAR', 'NEW', 'NEWS', 'NEXT', 'NEXTDIRECT', 'NEXUS', 'NF', 'NFL', 'NG', 'NGO', 'NHK', 'NI', 'NICO', 'NIKE', 'NIKON', 'NINJA', 'NISSAN', 'NISSAY', 'NL', 'NO', 'NOKIA', 'NORTHWESTERNMUTUAL', 'NORTON', 'NOW', 'NOWRUZ', 'NOWTV', 'NP', 'NR', 'NRA', 'NRW', 'NTT', 'NU', 'NYC', 'NZ', 'OBI', 'OBSERVER', 'OFFICE', 'OKINAWA', 'OLAYAN', 'OLAYANGROUP', 'OLDNAVY', 'OLLO', 'OM', 'OMEGA', 'ONE', 'ONG', 'ONL', 'ONLINE', 'OOO', 'OPEN', 'ORACLE', 'ORANGE', 'ORG', 'ORGANIC', 'ORIGINS', 'OSAKA', 'OTSUKA', 'OTT', 'OVH', 'PA', 'PAGE', 'PANASONIC', 'PARIS', 'PARS', 'PARTNERS', 'PARTS', 'PARTY', 'PASSAGENS', 'PAY', 'PCCW', 'PE', 'PET', 'PF', 'PFIZER', 'PG', 'PH', 'PHARMACY', 'PHD', 'PHILIPS', 'PHONE', 'PHOTO', 'PHOTOGRAPHY', 'PHOTOS', 'PHYSIO', 'PICS', 'PICTET', 'PICTURES', 'PID', 'PIN', 'PING', 'PINK', 'PIONEER', 'PIZZA', 'PK', 'PL', 'PLACE', 'PLAY', 'PLAYSTATION', 'PLUMBING', 'PLUS', 'PM', 'PN', 'PNC', 'POHL', 'POKER', 'POLITIE', 'PORN', 'POST', 'PR', 'PRAMERICA', 'PRAXI', 'PRESS', 'PRIME', 'PRO', 'PROD', 'PRODUCTIONS', 'PROF', 'PROGRESSIVE', 'PROMO', 'PROPERTIES', 'PROPERTY', 'PROTECTION', 'PRU', 'PRUDENTIAL', 'PS', 'PT', 'PUB', 'PW', 'PWC', 'PY', 'QA', 'QPON', 'QUEBEC', 'QUEST', 'RACING', 'RADIO', 'RE', 'READ', 'REALESTATE', 'REALTOR', 'REALTY', 'RECIPES', 'RED', 'REDSTONE', 'REDUMBRELLA', 'REHAB', 'REISE', 'REISEN', 'REIT', 'RELIANCE', 'REN', 'RENT', 'RENTALS', 'REPAIR', 'REPORT', 'REPUBLICAN', 'REST', 'RESTAURANT', 'REVIEW', 'REVIEWS', 'REXROTH', 'RICH', 'RICHARDLI', 'RICOH', 'RIL', 'RIO', 'RIP', 'RO', 'ROCHER', 'ROCKS', 'RODEO', 'ROGERS', 'ROOM', 'RS', 'RSVP', 'RU', 'RUGBY', 'RUHR', 'RUN', 'RW', 'RWE', 'RYUKYU', 'SA', 'SAARLAND', 'SAFE', 'SAFETY', 'SAKURA', 'SALE', 'SALON', 'SAMSCLUB', 'SAMSUNG', 'SANDVIK', 'SANDVIKCOROMANT', 'SANOFI', 'SAP', 'SARL', 'SAS', 'SAVE', 'SAXO', 'SB', 'SBI', 'SBS', 'SC', 'SCA', 'SCB', 'SCHAEFFLER', 'SCHMIDT', 'SCHOLARSHIPS', 'SCHOOL', 'SCHULE', 'SCHWARZ', 'SCIENCE', 'SCOT', 'SD', 'SE', 'SEARCH', 'SEAT', 'SECURE', 'SECURITY', 'SEEK', 'SELECT', 'SENER', 'SERVICES', 'SEVEN', 'SEW', 'SEX', 'SEXY', 'SFR', 'SG', 'SH', 'SHANGRILA', 'SHARP', 'SHAW', 'SHELL', 'SHIA', 'SHIKSHA', 'SHOES', 'SHOP', 'SHOPPING', 'SHOUJI', 'SHOW', 'SHOWTIME', 'SI', 'SILK', 'SINA', 'SINGLES', 'SITE', 'SJ', 'SK', 'SKI', 'SKIN', 'SKY', 'SKYPE', 'SL', 'SLING', 'SM', 'SMART', 'SMILE', 'SN', 'SNCF', 'SO', 'SOCCER', 'SOCIAL', 'SOFTBANK', 'SOFTWARE', 'SOHU', 'SOLAR', 'SOLUTIONS', 'SONG', 'SONY', 'SOY', 'SPA', 'SPACE', 'SPORT', 'SPOT', 'SR', 'SRL', 'SS', 'ST', 'STADA', 'STAPLES', 'STAR', 'STATEBANK', 'STATEFARM', 'STC', 'STCGROUP', 'STOCKHOLM', 'STORAGE', 'STORE', 'STREAM', 'STUDIO', 'STUDY', 'STYLE', 'SU', 'SUCKS', 'SUPPLIES', 'SUPPLY', 'SUPPORT', 'SURF', 'SURGERY', 'SUZUKI', 'SV', 'SWATCH', 'SWISS', 'SX', 'SY', 'SYDNEY', 'SYSTEMS', 'SZ', 'TAB', 'TAIPEI', 'TALK', 'TAOBAO', 'TARGET', 'TATAMOTORS', 'TATAR', 'TATTOO', 'TAX', 'TAXI', 'TC', 'TCI', 'TD', 'TDK', 'TEAM', 'TECH', 'TECHNOLOGY', 'TEL', 'TEMASEK', 'TENNIS', 'TEVA', 'TF', 'TG', 'TH', 'THD', 'THEATER', 'THEATRE', 'TIAA', 'TICKETS', 'TIENDA', 'TIFFANY', 'TIPS', 'TIRES', 'TIROL', 'TJ', 'TJMAXX', 'TJX', 'TK', 'TKMAXX', 'TL', 'TM', 'TMALL', 'TN', 'TO', 'TODAY', 'TOKYO', 'TOOLS', 'TOP', 'TORAY', 'TOSHIBA', 'TOTAL', 'TOURS', 'TOWN', 'TOYOTA', 'TOYS', 'TR', 'TRADE', 'TRADING', 'TRAINING', 'TRAVEL', 'TRAVELCHANNEL', 'TRAVELERS', 'TRAVELERSINSURANCE', 'TRUST', 'TRV', 'TT', 'TUBE', 'TUI', 'TUNES', 'TUSHU', 'TV', 'TVS', 'TW', 'TZ', 'UA', 'UBANK', 'UBS', 'UG', 'UK', 'UNICOM', 'UNIVERSITY', 'UNO', 'UOL', 'UPS', 'US', 'UY', 'UZ', 'VA', 'VACATIONS', 'VANA', 'VANGUARD', 'VC', 'VE', 'VEGAS', 'VENTURES', 'VERISIGN', 'VERSICHERUNG', 'VET', 'VG', 'VI', 'VIAJES', 'VIDEO', 'VIG', 'VIKING', 'VILLAS', 'VIN', 'VIP', 'VIRGIN', 'VISA', 'VISION', 'VIVA', 'VIVO', 'VLAANDEREN', 'VN', 'VODKA', 'VOLKSWAGEN', 'VOLVO', 'VOTE', 'VOTING', 'VOTO', 'VOYAGE', 'VU', 'VUELOS', 'WALES', 'WALMART', 'WALTER', 'WANG', 'WANGGOU', 'WATCH', 'WATCHES', 'WEATHER', 'WEATHERCHANNEL', 'WEBCAM', 'WEBER', 'WEBSITE', 'WED', 'WEDDING', 'WEIBO', 'WEIR', 'WF', 'WHOSWHO', 'WIEN', 'WIKI', 'WILLIAMHILL', 'WIN', 'WINDOWS', 'WINE', 'WINNERS', 'WME', 'WOLTERSKLUWER', 'WOODSIDE', 'WORK', 'WORKS', 'WORLD', 'WOW', 'WS', 'WTC', 'WTF', 'XBOX', 'XEROX', 'XFINITY', 'XIHUAN', 'XIN', 'XN--11B4C3D', 'XN--1CK2E1B', 'XN--1QQW23A', 'XN--2SCRJ9C', 'XN--30RR7Y', 'XN--3BST00M', 'XN--3DS443G', 'XN--3E0B707E', 'XN--3HCRJ9C', 'XN--3PXU8K', 'XN--42C2D9A', 'XN--45BR5CYL', 'XN--45BRJ9C', 'XN--45Q11C', 'XN--4DBRK0CE', 'XN--4GBRIM', 'XN--54B7FTA0CC', 'XN--55QW42G', 'XN--55QX5D', 'XN--5SU34J936BGSG', 'XN--5TZM5G', 'XN--6FRZ82G', 'XN--6QQ986B3XL', 'XN--80ADXHKS', 'XN--80AO21A', 'XN--80AQECDR1A', 'XN--80ASEHDB', 'XN--80ASWG', 'XN--8Y0A063A', 'XN--90A3AC', 'XN--90AE', 'XN--90AIS', 'XN--9DBQ2A', 'XN--9ET52U', 'XN--9KRT00A', 'XN--B4W605FERD', 'XN--BCK1B9A5DRE4C', 'XN--C1AVG', 'XN--C2BR7G', 'XN--CCK2B3B', 'XN--CCKWCXETD', 'XN--CG4BKI', 'XN--CLCHC0EA0B2G2A9GCD', 'XN--CZR694B', 'XN--CZRS0T', 'XN--CZRU2D', 'XN--D1ACJ3B', 'XN--D1ALF', 'XN--E1A4C', 'XN--ECKVDTC9D', 'XN--EFVY88H', 'XN--FCT429K', 'XN--FHBEI', 'XN--FIQ228C5HS', 'XN--FIQ64B', 'XN--FIQS8S', 'XN--FIQZ9S', 'XN--FJQ720A', 'XN--FLW351E', 'XN--FPCRJ9C3D', 'XN--FZC2C9E2C', 'XN--FZYS8D69UVGM', 'XN--G2XX48C', 'XN--GCKR3F0F', 'XN--GECRJ9C', 'XN--GK3AT1E', 'XN--H2BREG3EVE', 'XN--H2BRJ9C', 'XN--H2BRJ9C8C', 'XN--HXT814E', 'XN--I1B6B1A6A2E', 'XN--IMR513N', 'XN--IO0A7I', 'XN--J1AEF', 'XN--J1AMH', 'XN--J6W193G', 'XN--JLQ480N2RG', 'XN--JVR189M', 'XN--KCRX77D1X4A', 'XN--KPRW13D', 'XN--KPRY57D', 'XN--KPUT3I', 'XN--L1ACC', 'XN--LGBBAT1AD8J', 'XN--MGB9AWBF', 'XN--MGBA3A3EJT', 'XN--MGBA3A4F16A', 'XN--MGBA7C0BBN0A', 'XN--MGBAAKC7DVF', 'XN--MGBAAM7A8H', 'XN--MGBAB2BD', 'XN--MGBAH1A3HJKRD', 'XN--MGBAI9AZGQP6J', 'XN--MGBAYH7GPA', 'XN--MGBBH1A', 'XN--MGBBH1A71E', 'XN--MGBC0A9AZCG', 'XN--MGBCA7DZDO', 'XN--MGBCPQ6GPA1A', 'XN--MGBERP4A5D4AR', 'XN--MGBGU82A', 'XN--MGBI4ECEXP', 'XN--MGBPL2FH', 'XN--MGBT3DHD', 'XN--MGBTX2B', 'XN--MGBX4CD0AB', 'XN--MIX891F', 'XN--MK1BU44C', 'XN--MXTQ1M', 'XN--NGBC5AZD', 'XN--NGBE9E0A', 'XN--NGBRX', 'XN--NODE', 'XN--NQV7F', 'XN--NQV7FS00EMA', 'XN--NYQY26A', 'XN--O3CW4H', 'XN--OGBPF8FL', 'XN--OTU796D', 'XN--P1ACF', 'XN--P1AI', 'XN--PGBS0DH', 'XN--PSSY2U', 'XN--Q7CE6A', 'XN--Q9JYB4C', 'XN--QCKA1PMC', 'XN--QXA6A', 'XN--QXAM', 'XN--RHQV96G', 'XN--ROVU88B', 'XN--RVC1E0AM3E', 'XN--S9BRJ9C', 'XN--SES554G', 'XN--T60B56A', 'XN--TCKWE', 'XN--TIQ49XQYJ', 'XN--UNUP4Y', 'XN--VERMGENSBERATER-CTB', 'XN--VERMGENSBERATUNG-PWB', 'XN--VHQUV', 'XN--VUQ861B', 'XN--W4R85EL8FHU5DNRA', 'XN--W4RS40L', 'XN--WGBH1C', 'XN--WGBL6A', 'XN--XHQ521B', 'XN--XKC2AL3HYE2A', 'XN--XKC2DL3A5EE0H', 'XN--Y9A3AQ', 'XN--YFRO4I67O', 'XN--YGBI2AMMX', 'XN--ZFR164B', 'XXX', 'XYZ', 'YACHTS', 'YAHOO', 'YAMAXUN', 'YANDEX', 'YE', 'YODOBASHI', 'YOGA', 'YOKOHAMA', 'YOU', 'YOUTUBE', 'YT', 'YUN', 'ZA', 'ZAPPOS', 'ZARA', 'ZERO', 'ZIP', 'ZM', 'ZONE', 'ZUERICH', 'ZW']
function cleanTld(s) {
let i = s.lastIndexOf('.');
if(!i) return s; // no tld found
let tld = s.substring(i+1).toUpperCase();
if(tlds.includes(tld)) return s; // tld is OK
let longestTldMatch = tlds.filter(t=>tld.startsWith(t)).sort((a,b)=>a.length-b.length).pop();
if(!longestTldMatch) return s; // no matching tld found
return s.substring(0, i+1) + longestTldMatch.toLowerCase();
}
console.log(cleanTld('aa#aaa.'))
console.log(cleanTld('aa#aaa'))
console.log(cleanTld('aa#aaa.comwww'))
console.log(cleanTld('aa#aaa.com'))
console.log(cleanTld('aa#aaa.xcom'))
console.log(cleanTld('aa#aaa.co.ukwww'))
console.log(cleanTld('aa#aaa.ly'))
console.log(cleanTld('aa#aaa.lyuuu'))
Related
How to display selected country using select2?
I'm using select2 but not able to display selected country how can i do that? My Code:- (function($) { $(function() { var isoCountries = [ { id: '', text: 'Select Country'}, { id: 'AF', text: 'Afghanistan'}, { id: 'AL', text: 'Albania'}, { id: 'DZ', text: 'Algeria'}, { id: 'AS', text: 'American Samoa'}, { id: 'AD', text: 'Andorra'}, { id: 'AO', text: 'Angola'}, { id: 'AI', text: 'Anguilla'}, { id: 'AQ', text: 'Antarctica'}, { id: 'AG', text: 'Antigua And Barbuda'}, { id: 'AR', text: 'Argentina'}, { id: 'AM', text: 'Armenia'}, { id: 'AW', text: 'Aruba'}, { id: 'AU', text: 'Australia'}, { id: 'AT', text: 'Austria'}, { id: 'AZ', text: 'Azerbaijan'}, { id: 'BS', text: 'Bahamas'}, { id: 'BH', text: 'Bahrain'}, { id: 'BD', text: 'Bangladesh'}, { id: 'BB', text: 'Barbados'}, { id: 'BY', text: 'Belarus'}, { id: 'BE', text: 'Belgium'}, { id: 'BZ', text: 'Belize'}, { id: 'BJ', text: 'Benin'}, { id: 'BM', text: 'Bermuda'}, { id: 'BT', text: 'Bhutan'}, { id: 'BO', text: 'Bolivia'}, { id: 'BA', text: 'Bosnia And Herzegovina'}, { id: 'BW', text: 'Botswana'}, { id: 'BV', text: 'Bouvet Island'}, { id: 'BR', text: 'Brazil'}, { id: 'IO', text: 'British Indian Ocean Territory'}, { id: 'BN', text: 'Brunei Darussalam'}, { id: 'BG', text: 'Bulgaria'}, { id: 'BF', text: 'Burkina Faso'}, { id: 'BI', text: 'Burundi'}, { id: 'KH', text: 'Cambodia'}, { id: 'CM', text: 'Cameroon'}, { id: 'CA', text: 'Canada'}, { id: 'CV', text: 'Cape Verde'}, { id: 'KY', text: 'Cayman Islands'}, { id: 'CF', text: 'Central African Republic'}, { id: 'TD', text: 'Chad'}, { id: 'CL', text: 'Chile'}, { id: 'CN', text: 'China'}, { id: 'CX', text: 'Christmas Island'}, { id: 'CC', text: 'Cocos (Keeling) Islands'}, { id: 'CO', text: 'Colombia'}, { id: 'KM', text: 'Comoros'}, { id: 'CG', text: 'Congo'}, { id: 'CD', text: 'Congo}, Democratic Republic'}, { id: 'CK', text: 'Cook Islands'}, { id: 'CR', text: 'Costa Rica'}, { id: 'CI', text: 'Cote D\'Ivoire'}, { id: 'HR', text: 'Croatia'}, { id: 'CU', text: 'Cuba'}, { id: 'CY', text: 'Cyprus'}, { id: 'CZ', text: 'Czech Republic'}, { id: 'DK', text: 'Denmark'}, { id: 'DJ', text: 'Djibouti'}, { id: 'DM', text: 'Dominica'}, { id: 'DO', text: 'Dominican Republic'}, { id: 'EC', text: 'Ecuador'}, { id: 'SV', text: 'El Salvador'}, { id: 'GQ', text: 'Equatorial Guinea'}, { id: 'ER', text: 'Eritrea'}, { id: 'EE', text: 'Estonia'}, { id: 'ET', text: 'Ethiopia'}, { id: 'FK', text: 'Falkland Islands (Malvinas)'}, { id: 'FO', text: 'Faroe Islands'}, { id: 'FJ', text: 'Fiji'}, { id: 'FI', text: 'Finland'}, { id: 'FR', text: 'France'}, { id: 'GF', text: 'French Guiana'}, { id: 'PF', text: 'French Polynesia'}, { id: 'TF', text: 'French Southern Territories'}, { id: 'GA', text: 'Gabon'}, { id: 'GM', text: 'Gambia'}, { id: 'GE', text: 'Georgia'}, { id: 'DE', text: 'Germany'}, { id: 'GH', text: 'Ghana'}, { id: 'GI', text: 'Gibraltar'}, { id: 'GR', text: 'Greece'}, { id: 'GL', text: 'Greenland'}, { id: 'GD', text: 'Grenada'}, { id: 'GP', text: 'Guadeloupe'}, { id: 'GU', text: 'Guam'}, { id: 'GT', text: 'Guatemala'}, { id: 'GN', text: 'Guinea'}, { id: 'GW', text: 'Guinea-Bissau'}, { id: 'GY', text: 'Guyana'}, { id: 'HT', text: 'Haiti'}, { id: 'HM', text: 'Heard Island & Mcdonald Islands'}, { id: 'VA', text: 'Holy See (Vatican City State)'}, { id: 'HN', text: 'Honduras'}, { id: 'HK', text: 'Hong Kong'}, { id: 'HU', text: 'Hungary'}, { id: 'IS', text: 'Iceland'}, { id: 'IN', text: 'India'}, { id: 'ID', text: 'Indonesia'}, { id: 'IR', text: 'Iran}, Islamic Republic Of'}, { id: 'IQ', text: 'Iraq'}, { id: 'IE', text: 'Ireland'}, { id: 'IL', text: 'Israel'}, { id: 'IT', text: 'Italy'}, { id: 'JM', text: 'Jamaica'}, { id: 'JP', text: 'Japan'}, { id: 'JO', text: 'Jordan'}, { id: 'KZ', text: 'Kazakhstan'}, { id: 'KI', text: 'Kiribati'}, { id: 'KR', text: 'Korea'}, { id: 'KW', text: 'Kuwait'}, { id: 'LA', text: 'Lao People\'s Democratic Republic'}, { id: 'LV', text: 'Latvia'}, { id: 'LB', text: 'Lebanon'}, { id: 'LS', text: 'Lesotho'}, { id: 'LR', text: 'Liberia'}, { id: 'LY', text: 'Libyan Arab Jamahiriya'}, { id: 'LI', text: 'Liechtenstein'}, { id: 'LT', text: 'Lithuania'}, { id: 'LU', text: 'Luxembourg'}, { id: 'MO', text: 'Macao'}, { id: 'MK', text: 'Macedonia'}, { id: 'MG', text: 'Madagascar'}, { id: 'MW', text: 'Malawi'}, { id: 'MY', text: 'Malaysia'}, { id: 'MV', text: 'Maldives'}, { id: 'ML', text: 'Mali'}, { id: 'MT', text: 'Malta'}, { id: 'MH', text: 'Marshall Islands'}, { id: 'MQ', text: 'Martinique'}, { id: 'MR', text: 'Mauritania'}, { id: 'MU', text: 'Mauritius'}, { id: 'MX', text: 'Mexico'}, { id: 'FM', text: 'Micronesia}, Federated States Of'}, { id: 'MD', text: 'Moldova'}, { id: 'MC', text: 'Monaco'}, { id: 'MN', text: 'Mongolia'}, { id: 'ME', text: 'Montenegro'}, { id: 'MS', text: 'Montserrat'}, { id: 'MA', text: 'Morocco'}, { id: 'MZ', text: 'Mozambique'}, { id: 'MM', text: 'Myanmar'}, { id: 'NA', text: 'Namibia'}, { id: 'NR', text: 'Nauru'}, { id: 'NP', text: 'Nepal'}, { id: 'NL', text: 'Netherlands'}, { id: 'AN', text: 'Netherlands Antilles'}, { id: 'NC', text: 'New Caledonia'}, { id: 'NZ', text: 'New Zealand'}, { id: 'NI', text: 'Nicaragua'}, { id: 'NE', text: 'Niger'}, { id: 'NG', text: 'Nigeria'}, { id: 'NU', text: 'Niue'}, { id: 'NF', text: 'Norfolk Island'}, { id: 'MP', text: 'Northern Mariana Islands'}, { id: 'NO', text: 'Norway'}, { id: 'OM', text: 'Oman'}, { id: 'PK', text: 'Pakistan'}, { id: 'PW', text: 'Palau'}, { id: 'PA', text: 'Panama'}, { id: 'PG', text: 'Papua New Guinea'}, { id: 'PY', text: 'Paraguay'}, { id: 'PE', text: 'Peru'}, { id: 'PH', text: 'Philippines'}, { id: 'PN', text: 'Pitcairn'}, { id: 'PL', text: 'Poland'}, { id: 'PT', text: 'Portugal'}, { id: 'PR', text: 'Puerto Rico'}, { id: 'QA', text: 'Qatar'}, { id: 'RE', text: 'Reunion'}, { id: 'RO', text: 'Romania'}, { id: 'RU', text: 'Russian Federation'}, { id: 'RW', text: 'Rwanda'}, { id: 'SH', text: 'Saint Helena'}, { id: 'KN', text: 'Saint Kitts And Nevis'}, { id: 'LC', text: 'Saint Lucia'}, { id: 'PM', text: 'Saint Pierre And Miquelon'}, { id: 'VC', text: 'Saint Vincent And Grenadines'}, { id: 'WS', text: 'Samoa'}, { id: 'SM', text: 'San Marino'}, { id: 'ST', text: 'Sao Tome And Principe'}, { id: 'SA', text: 'Saudi Arabia'}, { id: 'SN', text: 'Senegal'}, { id: 'RS', text: 'Serbia'}, { id: 'SC', text: 'Seychelles'}, { id: 'SL', text: 'Sierra Leone'}, { id: 'SG', text: 'Singapore'}, { id: 'SK', text: 'Slovakia'}, { id: 'SI', text: 'Slovenia'}, { id: 'SB', text: 'Solomon Islands'}, { id: 'SO', text: 'Somalia'}, { id: 'ZA', text: 'South Africa'}, { id: 'GS', text: 'South Georgia And Sandwich Isl.'}, { id: 'ES', text: 'Spain'}, { id: 'LK', text: 'Sri Lanka'}, { id: 'SD', text: 'Sudan'}, { id: 'SR', text: 'Suriname'}, { id: 'SJ', text: 'Svalbard And Jan Mayen'}, { id: 'SZ', text: 'Swaziland'}, { id: 'SE', text: 'Sweden'}, { id: 'CH', text: 'Switzerland'}, { id: 'SY', text: 'Syrian Arab Republic'}, { id: 'TW', text: 'Taiwan'}, { id: 'TJ', text: 'Tajikistan'}, { id: 'TZ', text: 'Tanzania'}, { id: 'TH', text: 'Thailand'}, { id: 'TL', text: 'Timor-Leste'}, { id: 'TG', text: 'Togo'}, { id: 'TK', text: 'Tokelau'}, { id: 'TO', text: 'Tonga'}, { id: 'TT', text: 'Trinidad And Tobago'}, { id: 'TN', text: 'Tunisia'}, { id: 'TR', text: 'Turkey'}, { id: 'TM', text: 'Turkmenistan'}, { id: 'TC', text: 'Turks And Caicos Islands'}, { id: 'TV', text: 'Tuvalu'}, { id: 'UG', text: 'Uganda'}, { id: 'UA', text: 'Ukraine'}, { id: 'AE', text: 'United Arab Emirates'}, { id: 'GB', text: 'United Kingdom'}, { id: 'US', text: 'United States'}, { id: 'UM', text: 'United States Outlying Islands'}, { id: 'UY', text: 'Uruguay'}, { id: 'UZ', text: 'Uzbekistan'}, { id: 'VU', text: 'Vanuatu'}, { id: 'VE', text: 'Venezuela'}, { id: 'VN', text: 'Viet Nam'}, { id: 'VG', text: 'Virgin Islands}, British'}, { id: 'VI', text: 'Virgin Islands}, U.S.'}, { id: 'WF', text: 'Wallis And Futuna'}, { id: 'EH', text: 'Western Sahara'}, { id: 'YE', text: 'Yemen'}, { id: 'ZM', text: 'Zambia'}, { id: 'ZW', text: 'Zimbabwe'} ]; function formatCountry (country) { if (!country.id) { return country.text; } var $country = $( '<span class="flag flag-'+ country.id.toLowerCase() +'"></span>' + '<span class="flag-text">'+ country.text+"</span>" ); return $country; }; //Assuming you have a select element with name country // e.g. <select name="name"></select> // $('body .select2-container .select2-results_options').addClass('.top-flag-list'); var $select2 = $("[name='country']").select2({ templateResult: formatCountry, data: isoCountries, placeholder: "Select Country" }); // $select2.data('select2').$container.addClass("wrap"); }); })(jQuery); <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> <select name="country" class="form-control top-flag-list" data-country-old="<?php echo $country; ?>"> Thank you so much for your efforts!
How to get questions based on category, subcategory, sub subcategory etc from a JSON file for a quiz
I am using js, html, CSS and JSON for making a question bank of different categories and levels of difficulty. I have made a quiz question Bank in JSON - quizquestion.json - with options, levels of difficulty and different categories, sub categories and sub sub category. I want to select categories, subcategories,.... and level of difficulty for the quiz. I have included the selection in HTML as follows: <label for="categories">Choose category</label> <select name="categories" id="categories"> <option value="GK">General Knowledge</option> <option value="science">Science</option> <option value="history">History</option> </select> <p> <label for="levels">Choose difficulty level</label> <select name="levels" id="levels"> <option value="easy">Easy</option> <option value="mod">Moderate</option> <option value="hard">Hard</option> </select> </p> I am loading the json file and assigning the questions and answers as follows. But I want to render questions of one category of one difficulty level. How do I do it? $.getJSON('quizquestion.json', function(data) { for(i=0;i<data.quizquestions.length;i++) { qBank[i] =new Array; qBank[i][0] = data.quizquestions[i].question; qBank[i][1] = data.quizquestions[i].option1; qBank[i][2] = data.quizquestions[i].option2; qBank[i][3] = data.quizquestions[i].option3; qBank[i][4] = data.quizquestions[i].option4; } renderQuestion(); }) Small portion of JSON file is as follows : { quizquestions : [ { category: 'science', 'sub-category0': 'physics', 'sub-category1': 'light', levels: 'easy' , question: 'Which color is not part of VIBGYOR', answer: 'Brown' , option1: 'Violet', option2: 'Red', option3: 'Orange', option4: 'Brown' } , { category: 'science', 'sub-category0': 'physics', 'sub-category1': 'energy', levels: 'moderate' , question: 'Which form of energy is renewable form of energy?', answer: 'solar' , option1: 'electric', option2: 'solar', option3: 'coal', option4: 'petroleum' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'hard' , question: 'Gold is represented in the periodic table by which Symbol?', answer: 'Au' , option1: 'Go', option2: 'Au', option3: 'Ye', option4: 'ld' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'moderate' , question: 'Tin is represented in the periodic table by which Symbol?', answer: 'Sb' , option1: 'Go', option2: 'Au', option3: 'Sb', option4: 'ld' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'easy' , question: 'Lead is represented in the periodic table by which Symbol?', answer: 'Pb' , option1: 'Pb', option2: 'Au', option3: 'Sb', option4: 'ld' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'worldwar', levels: 'hard' , question: 'Where were the atom bombs dropped?', answer: 'Japan' , option1: 'Germany', option2: 'Poland', option3: 'Russia', option4: 'Japan' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'When did USA become independent?', answer: '1776' , option1: '1774', option2: '1776', option3: '1876', option4: '1879' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'Who was the first presidnet of USA?', answer: 'George Washington' , option1: 'John Adams', option2: 'Thomas Jefferson', option3: 'George Washington', option4: 'James Madison' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'What is the capital of USA?', answer: 'Washington' , option1: 'New York', option2: 'Washington', option3: 'Chicago', option4: 'California' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'easy' , question: 'What is the capital of France?', answer: 'Paris' , option1: 'Paris', option2: 'London', option3: 'Brussels', option4: 'Moscow' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'easy' , question: 'What is the capital of Russia?', answer: 'Moscow' , option1: 'Paris', option2: 'London', option3: 'Brussels', option4: 'Moscow' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'easy' , question: 'What is the capital of Portugal?', answer: 'Lisbon' , option1: 'Paris', option2: 'London', option3: 'Lisbon', option4: 'Moscow' } ] } For example, if I want to select easy level for category-general knowledge, sub category-Europe, sub sub category - capital, how do I render the question or execute it?
For your example you can do this, for the other conditions just change the parameters. var quizquestions = [ { category: 'science', 'sub-category0': 'physics', 'sub-category1': 'light', levels: 'easy' , question: 'Which color is not part of VIBGYOR', answer: 'Brown' , option1: 'Violet', option2: 'Red', option3: 'Orange', option4: 'Brown' } , { category: 'science', 'sub-category0': 'physics', 'sub-category1': 'energy', levels: 'moderate' , question: 'Which form of energy is renewable form of energy?', answer: 'solar' , option1: 'electric', option2: 'solar', option3: 'coal', option4: 'petroleum' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'hard' , question: 'Gold is represented in the periodic table by which Symbol?', answer: 'Au' , option1: 'Go', option2: 'Au', option3: 'Ye', option4: 'ld' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'moderate' , question: 'Tin is represented in the periodic table by which Symbol?', answer: 'Sb' , option1: 'Go', option2: 'Au', option3: 'Sb', option4: 'ld' } , { category: 'science', 'sub-category0': 'chemistry', 'sub-category1': 'Elements', levels: 'easy' , question: 'Lead is represented in the periodic table by which Symbol?', answer: 'Pb' , option1: 'Pb', option2: 'Au', option3: 'Sb', option4: 'ld' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'worldwar', levels: 'hard' , question: 'Where were the atom bombs dropped?', answer: 'Japan' , option1: 'Germany', option2: 'Poland', option3: 'Russia', option4: 'Japan' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'When did USA become independent?', answer: '1776' , option1: '1774', option2: '1776', option3: '1876', option4: '1879' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'Who was the first presidnet of USA?', answer: 'George Washington' , option1: 'John Adams', option2: 'Thomas Jefferson', option3: 'George Washington', option4: 'James Madison' } , { category: 'social science', 'sub-category0': 'history', 'sub-category1': 'USA', levels: 'hard' , question: 'What is the capital of USA?', answer: 'Washington' , option1: 'New York', option2: 'Washington', option3: 'Chicago', option4: 'California' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'easy' , question: 'What is the capital of France?', answer: 'Paris' , option1: 'Paris', option2: 'London', option3: 'Brussels', option4: 'Moscow' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'easy' , question: 'What is the capital of Russia?', answer: 'Moscow' , option1: 'Paris', option2: 'London', option3: 'Brussels', option4: 'Moscow' } , { category: 'general knowledge', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'moderate' , question: 'What is the capital of Portugal?', answer: 'Lisbon' , option1: 'Paris', option2: 'London', option3: 'Lisbon', option4: 'Moscow' } , { category: 'history', 'sub-category0': 'capital', 'sub-category1': 'Europe', levels: 'hard' , question: 'What is the capital of Portugal?', answer: 'Lisbon' , option1: 'Paris', option2: 'London', option3: 'Lisbon', option4: 'Moscow' } ]; function changeEvent(){ var category = document.getElementById("categories").value; var level = document.getElementById("levels").value; // for easy, general knowledge, capital, Europe var filteredQuestions = quizquestions.filter( (question) => question.levels == level && question.category == category // && question["sub-category0"] == "capital" // && question["sub-category1"] == "Europe" ); // print the list. document.getElementById("list").innerHTML = JSON.stringify(filteredQuestions); } <label for="categories">Choose category</label> <select name="categories" id="categories" onchange="changeEvent()"> <option value="general knowledge">General Knowledge</option> <option value="science">Science</option> <option value="history">History</option> </select> <p> <label for="levels">Choose difficulty level</label> <select name="levels" id="levels" onchange="changeEvent()"> <option value="easy">Easy</option> <option value="moderate">Moderate</option> <option value="hard">Hard</option> </select> </p> <pre> <code id="list"> </code> </pre>
JavaScript group data into tree view 2 levels deep
I have a JSON object like this: { id: '1', items: [ { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }, { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 } ] }, { id: '2', items: [ { id: '2', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '556', categoryDescription: 'my category 6', qty: 10, saleValue: 200 } ] }, { id: '3', items: [ { venueId: '3', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '557', categoryDescription: 'my category 7', qty: 10, saleValue: 200 } ] }; I want to make this into a new JSON object where everything is grouped by id (it already is but I need the number to become the key) then by categoryCode so the result looks something like this: { '1': { '555': { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 } } } Is there a simple way to do this either using lodash or just plain JavaScript or some NPM package?
I create a general function that receiving array of items and parse it based on attrKeys and infoKeys array: const data = [{ id: '1', items: [{ id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }, { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }] }, { id: '2', items: [{ id: '2', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '556', categoryDescription: 'my category 6', qty: 10, saleValue: 200 }] }, { id: '3', items: [{ venueId: '3', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '557', categoryDescription: 'my category 7', qty: 10, saleValue: 200 }] }]; const transformData = (input, attrKeys = [], infoKeys = [], deep = 0) => { if (input && typeof input === 'object' && input.length) { const key1 = attrKeys[deep]; const key2 = infoKeys[deep]; deep++; const output = {} input.forEach(i => { const info = i[key2] ? transformData(i[key2], attrKeys, infoKeys, deep) : i; output[`${i[key1]}`] = info; }); return output; } return input; }; //What you want is here const transformedData = transformData(data, ['id','categoryCode'], ['items']) console.log({transformedData})
Follow the nested for...of loop approach: const data = [{ id: '1', items: [{ id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }, { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }] }, { id: '2', items: [{ id: '2', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '556', categoryDescription: 'my category 6', qty: 10, saleValue: 200 }] }, { id: '3', items: [{ venueId: '3', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '557', categoryDescription: 'my category 7', qty: 10, saleValue: 200 }] }]; let finalData = {}; for (let obj of data) { finalData[obj.id] = {}; for (var item of obj.items) { finalData[obj.id][item.categoryCode] = { ...item }; } } console.log(finalData);
You can use Array.reduce function to achieve it. const array = [{ id: '1', items: [ { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }, { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 } ] }, { id: '2', items: [ { id: '2', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '556', categoryDescription: 'my category 6', qty: 10, saleValue: 200 } ] }, { id: '3', items: [ { id: '3', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '557', categoryDescription: 'my category 7', qty: 10, saleValue: 200 } ] }]; console.log( array // flatten the items array .reduce((prev, curr) => { return prev.concat(curr.items); }, []) .reduce((prev, curr) => { if (!prev[curr.id]) prev[curr.id] = {}; if (!prev[curr.id][curr.categoryCode]) prev[curr.id][curr.categoryCode] = {}; prev[curr.id][curr.categoryCode] = curr; return prev; }, {}) );
Alternatively, you can archive that by just 7 lines of code using reduce function. const array = [ { id: '1', items: [ { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 }, { id: '1', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '555', categoryDescription: 'my category', qty: 10, saleValue: 200 } ] }, { id: '2', items: [ { id: '2', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '556', categoryDescription: 'my category 6', qty: 10, saleValue: 200 } ] }, { id: '3', items: [ { venueId: '3', saleId: '123', saleIdAndItemId: '123456', locationId: '123', itemCode: '456', itemDescription: 'my item', categoryCode: '557', categoryDescription: 'my category 7', qty: 10, saleValue: 200 } ] } ]; console.log( array.reduce((prev, curr) => { prev[curr.id] = curr.items.reduce((prev, curr) => { (prev[curr.categoryCode] = []).push(curr); return prev; }, {}); return prev; }, {}) );
Map an array with parent Owner property to and Array with children property
Hi I am trying to map an array which is as below: var currentModel = [{id: 'Iron Man (CPC Avengers)', label: 'Iron Man', unit: 'CPC Avengers', level: '2', parent: '', children: []}, {id: 'Thor (Avengers Core Asgard)', label: 'Thor', unit: 'Avengers Core Asgard', level: '3', parent: 'Iron Man', children: []}, {id: 'Loki (Avengers Asgard)', label: 'Loki', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: []}, {id: 'Hela (Avengers Asgard)', label: 'Hela', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: []}, {id: 'Groot (Guardians of Galaxy)', label: 'Groot', unit: 'Guardians of Galaxy', 'level: '5', parent: 'Loki', children: []}, {id: 'Captain America (Avengers Core Earth)', label: 'Captain America', unit: 'Avengers Core Earth', level: '3', parent: 'Iron Man', children: []}, {id: 'Black Widow (Avengers Earth)', label: 'Black Widow', unit: 'Avengers Earth', level: '4', parent: 'Captain America', children: []}, {id: 'Hulk (Avengers Earth)', label: 'Hulk', unit: 'Avengers Earth', level: '4', parent: 'Captain America', children: []}] Into Below Array var requiredModel = [ {id: 'Iron Man (CPC Avengers)', label: 'Iron Man', unit: 'CPC Avengers', level: '2', parent: '', children: [ { id: 'Thor (Avengers Core Asgard)', label: 'Thor', unit: 'Avengers Core Asgard', level: '3', parent: 'Iron Man', children: [ { id: 'Loki (Avengers Asgard)', label: 'Loki', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: [ { id: 'Groot (Guardians of Galaxy)', label: 'Groot', unit: 'Guardians of Galaxy', level: '5', parent: 'Loki', children: []} ]}, {id: 'Hela (Avengers Asgard)', label: 'Hela', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: []}]},{id: 'Captain America (Avengers Core Earth)', label: 'Captain America', unit: 'Avengers Core Earth', level: '3', parent: 'Iron Man', children: [{ id: 'Black Widow (Avengers Earth)', label: 'Black Widow', unit: 'Avengers Earth', level: '4', parent: 'Captain America', children:[]}, { id: 'Hulk (Avengers Earth)', label: 'Hulk', unit: 'Avengers Earth', level: '4', children: []}]}]}] I tried following things on currentModel: Step1: To have separate array with respective levels var currentModelLvl2= currentModel.filter(function(item){ return item.level === '2'}); var currentModelLvl3= currentModel.filter(function(item){ return item.level === '3'}); var currentModelLvl4= currentModel.filter(function(item){ return item.level === '4'}); var currentModelLvl5= currentModel.filter(function(item){ return item.level === '5'}); Step2: Loop over currentModelLvl4 and currentModelLvl5 and add to the children array of currentModelLvl4 the items from currentModelLvl5 where currentModelLvl4.label === currentModelLvl5.parent for (var i = 0; i < currentModelLvl4.length; i++) { var currentModelItem4 = currentModelLvl4[i]; for (var j = 0; j < currentModelLvl5.length; j++) { var currentModelItem5 = currentModelLvl4[j]; if (currentModelItem4.label === currentModelItem5.parent) { currentModelItem4.children.push( currentModelItem5); } }} But my loop gets stuck and makes my browser crash is anything wrong with my method or is there a better way to do this.
var currentModel = [{id: 'Iron Man (CPC Avengers)', label: 'Iron Man', unit: 'CPC Avengers', level: '2', parent: '', children: []}, {id: 'Thor (Avengers Core Asgard)', label: 'Thor', unit: 'Avengers Core Asgard', level: '3', parent: 'Iron Man', children: []}, {id: 'Loki (Avengers Asgard)', label: 'Loki', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: []}, {id: 'Hela (Avengers Asgard)', label: 'Hela', unit: 'Avengers Asgard', level: '4', parent: 'Thor', children: []}, {id: 'Groot (Guardians of Galaxy)', label: 'Groot', unit: 'Guardians of Galaxy', level: '5', parent: 'Loki', children: []}, {id: 'Captain America (Avengers Core Earth)', label: 'Captain America', unit: 'Avengers Core Earth', level: '3', parent: 'Iron Man', children: []}, {id: 'Black Widow (Avengers Earth)', label: 'Black Widow', unit: 'Avengers Earth', level: '4', parent: 'Captain America', children: []}, {id: 'Hulk (Avengers Earth)', label: 'Hulk', unit: 'Avengers Earth', level: '4', parent: 'Captain America', children: []}]; var children = {}; currentModel.forEach(model => { children[model.parent] = children[model.parent] || []; children[model.parent].push(model); children[model.label] = model.children = children[model.label] || model.children; }); console.log(children[""]);
this should do it var values = [{ "id": "uniqueParentId1", "children": [{ "childProp1": "test1", "childProp2": "test3" }] }, { "id": "uniqueParentId2", "children": [{ "childProp1": "somevals", "childProp2": "other vals" }, { "childProp1": "somevals 1", "childProp2": "other vals 1" } ] } ]; var result = values.map(value => value.children.map(child => Object.assign({ parentId: value.id }, child)) ).reduce((l, n) => l.concat(n), []); console.log(result);
How can I highlight a DataTable row when a user clicks on it in AlloyUI 3.0.x?
The AlloyUI 1.5.x showcase demonstrates how to highlight rows in its "Real World" example. The example uses the DataTableSelection plugin with selectRows: true, however, that code no longer works in AlloyUI 3.0.x. I have tried using the DataTable.Highlight module with highlightRows: true, but that only highlights rows on mouseover: YUI().use('aui-datatable', 'datatable-highlight', function(Y) { /* ...code here... */ var dataTable = new Y.DataTable({ /* ...code here... */ highlightRows: true }).render('#myDataTable'); }); See runnable example (modified from the "Real World" DataTable example on alloyui.com): YUI().use( 'aui-datatable', 'datatable-highlight', function(Y) { var remoteData = [{ active: 'yes', address: '1236 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['banana', 'cherry'], last_login: '4/19/2007', name: 'John A. Smith', state: 'CA' }, { active: 'maybe', address: '9996 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['cherry'], last_login: ['4/10/2007'], name: 'Bob C. Uncle', state: 'CA' }, { active: 'yes', address: '1623 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['cherry'], last_login: '4/19/2007', name: 'John D. Smith', state: 'CA' }, { active: 'no', address: '3217 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['apple', 'cherry'], last_login: '2/15/2006', name: 'Joan E. Jones', state: 'NY' }, { active: 'maybe', address: '9899 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['banana'], last_login: '1/23/2004', name: 'Bob F. Uncle', state: 'CA' }, { active: 'yes', address: '1723 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['apple'], last_login: '4/19/2007', name: 'John G. Smith', state: 'CA' }, { active: 'no', address: '3241 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['kiwi'], last_login: '2/15/2006', name: 'Joan H. Jones', state: 'NY' }, { active: 'maybe', address: '9909 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['apple', 'banana'], last_login: '1/23/2004', name: 'Bob I. Uncle', state: 'CA' }, { active: 'yes', address: '1623 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['apple', 'cherry'], last_login: '4/19/2007', name: 'John J. Smith', state: 'CA' }, { active: 'no', address: '3721 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['banana'], last_login: '2/15/2006', name: 'Joan K. Jones', state: 'NY' }]; var states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']; var nestedCols = [{ key: 'name' }, { key: 'address' }, { key: 'city' }, { key: 'state' }, { key: 'amount' }]; var dataTable = new Y.DataTable({ columns: nestedCols, data: remoteData, highlightRows: true }).render('#myDataTable'); } ); <script src="http://cdn.alloyui.com/3.0.1/aui/aui-min.js"></script> <link href="http://cdn.alloyui.com/3.0.1/aui-css/css/bootstrap.min.css" rel="stylesheet"></link> <div class="yui3-skin-sam"> <div id="myDataTable"></div> </div> How can I highlight a row when a user clicks on it in AlloyUI 3.0.x?
You need to use the DataTableHighlight module with type: 'rows' instead: YUI().use('aui-datatable', 'aui-datatable-highlight', function(Y) { /* ...your code here... */ var dataTable = new Y.DataTable({ /* ...your code here... */ plugins: [{ cfg: { type: 'rows' }, fn: Y.Plugin.DataTableHighlight }] }).render('#myDataTable'); }); Here's a runnable example using your code: YUI().use( 'aui-datatable', 'aui-datatable-highlight', function(Y) { var remoteData = [{ active: 'yes', address: '1236 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['banana', 'cherry'], last_login: '4/19/2007', name: 'John A. Smith', state: 'CA' }, { active: 'maybe', address: '9996 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['cherry'], last_login: ['4/10/2007'], name: 'Bob C. Uncle', state: 'CA' }, { active: 'yes', address: '1623 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['cherry'], last_login: '4/19/2007', name: 'John D. Smith', state: 'CA' }, { active: 'no', address: '3217 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['apple', 'cherry'], last_login: '2/15/2006', name: 'Joan E. Jones', state: 'NY' }, { active: 'maybe', address: '9899 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['banana'], last_login: '1/23/2004', name: 'Bob F. Uncle', state: 'CA' }, { active: 'yes', address: '1723 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['apple'], last_login: '4/19/2007', name: 'John G. Smith', state: 'CA' }, { active: 'no', address: '3241 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['kiwi'], last_login: '2/15/2006', name: 'Joan H. Jones', state: 'NY' }, { active: 'maybe', address: '9909 Random Road', amount: 0, city: 'Los Angeles', colors: ['green'], fruit: ['apple', 'banana'], last_login: '1/23/2004', name: 'Bob I. Uncle', state: 'CA' }, { active: 'yes', address: '1623 Some Street', amount: 5, city: 'San Francisco', colors: ['red'], fruit: ['apple', 'cherry'], last_login: '4/19/2007', name: 'John J. Smith', state: 'CA' }, { active: 'no', address: '3721 Another Ave', amount: 3, city: 'New York', colors: ['red', 'blue'], fruit: ['banana'], last_login: '2/15/2006', name: 'Joan K. Jones', state: 'NY' }]; var states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']; var nestedCols = [{ key: 'name' }, { key: 'address' }, { key: 'city' }, { key: 'state' }, { key: 'amount' }]; var dataTable = new Y.DataTable({ columns: nestedCols, data: remoteData, plugins: [{ cfg: { type: 'rows' }, fn: Y.Plugin.DataTableHighlight }] }).render('#myDataTable'); dataTable.get('boundingBox').unselectable(); } ); <script src="http://cdn.alloyui.com/3.0.1/aui/aui-min.js"></script> <link href="http://cdn.alloyui.com/3.0.1/aui-css/css/bootstrap.min.css" rel="stylesheet"></link> <div class="yui3-skin-sam"> <div id="myDataTable"></div> </div>