Please, help.
Why are numbers displayed without a space?
How to make phone numbers displayed through a space?
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb);
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
console.info(re("SHOW"));
// ["Ivan: 555-10-01, 555-10-03, 555-10-02"]
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb).join(', ');
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
console.info(re("SHOW"));
Your code works as expected. If you just need the phone numbers printed then get the value of the phone number by accessing it:
var phoneBook = {};
function re(command) {
if (command.split(" ")[0] == "ADD") {
var name = command.split(" ")[1];
var numb = command.split(" ")[2].split(",");
if (!phoneBook.hasOwnProperty(name)) {
phoneBook[name] = numb;
return phoneBook[name];
} else {
phoneBook[name] = phoneBook[name].concat(numb);
return Object.keys(phoneBook) + ": " + phoneBook[name];
}
}
if (command.split(" ")[0] == "SHOW") {
var book = [];
for (i = 0; i < Object.keys(phoneBook).length; i++) {
var key = Object.keys(phoneBook)[i];
book[i] = [key + ": " + phoneBook[key]];
}
return book;
}
}
re("ADD Ivan 555-10-01,555-10-03");
re("ADD Ivan 555-10-02");
//get the full result
console.info(re("SHOW"));
console.info(re("SHOW")[0][0]);
Related
I am using the following library to implement multilingualism in my test website. However, there are some shortcomings that are difficult to deal with with my little experience.
The script works in such a way that we have a default language, it is written directly to html and dictionaries are made for other languages(they are at the very end of the js code). Everything works fine except for the title. When we want to switch to the default language, the title does not change, only after reloading the page it changes.
Most likely, the matter is in the following piece of code(184-186 line):
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
I suppose we need to add else and somehow set for it a value that is written in the html itself, but not which js changed in the translation.
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
Title: "Заголовок",
firstmessage: "ЭТО ЯЗЫК ПО УМОЛЧАНИЮ",
secondmessage: "КАКОЙ ТО ДРУГОЙ ТЕКСТ",
thirdmessage: "ЧТО ТО ЕЩЕ"
});
languative.modifyDictionary("de", {
Title: "Überschrift",
firstmessage: "Dies ist die Standardsprache",
secondmessage: "JEDER ANDERE TEXT",
thirdmessage: "ETWAS ANDERES"
});
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<h1 data-phrase-id="firstmessage">THIS IS THE DEFAULT LANGUAGE</h1>
<span data-phrase-id="secondmessage">ANY OTHER TEXT</span>
<p data-phrase-id="thirdmessage">SOMETHING ELSE</p>
Also on my website there is a feedback form. I would like it to be possible to translate the placeholder values. How to do it?
I got it like this, but is this a good way?
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
document.querySelector('.lang').onclick = function() {
if ((localStorage.getItem("lang") == "de") || (window.navigator.userLanguage == "de") || (window.navigator.language) == "de") {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Thema";
document.querySelector("input[name=message]").placeholder = "Brief";
} else if ((localStorage.getItem("lang") == "ru") || (window.navigator.userLanguage == "ru") || (window.navigator.language) == "ru") {
document.querySelector("input[name=name]").placeholder = "Имя";
document.querySelector("input[name=subject]").placeholder = "Тема";
document.querySelector("input[name=message]").placeholder = "Сообщение";
} else {
document.querySelector("input[name=name]").placeholder = "Name";
document.querySelector("input[name=subject]").placeholder = "Subject";
document.querySelector("input[name=message]").placeholder = "Message";
};
};
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
}
}
} else {
tag.innerHTML = " " + phrase + " ";
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
For the first snippet you should just add a dictionary for en containing the Title and it will work, like so:
languative.modifyDictionary("en", {
Title: "Caption",
});
For the second one, there is more work because your script change innerHTML, which is not suitable for your feedback form since it contains only input elements which doesn't have innerHTML, so the script should be modified accordingly, like so:
var languative;
(function (languative) {
var phraseIdAttr = "data-phrase-id";
languative.ignoreTags = {
img: "<img />",
br: "<br />",
hr: "<hr />"
};
languative.dictonaries = {
html: {
_id: "html",
_name: "HTML"
},
en: {
_id: "en",
_name: "English"
},
ru: {
_id: "ru",
_name: "Русский - Russian"
},
de: {
_id: "de",
_name: "Deutsche - German"
}
};
languative.selectedDictionary = null;
function getDictionary(langKey) {
langKey = langKey.toLowerCase();
if (langKey in languative.dictonaries)
return languative.dictonaries[langKey];
var sep = langKey.indexOf("-");
if (sep > 0)
langKey = langKey.substring(0, sep);
return languative.dictonaries[langKey];
}
languative.getDictionary = getDictionary;
function getPhrase(phraseId) {
var res = findPhrase(phraseId);
if (res)
return res; else
return phraseId;
}
languative.getPhrase = getPhrase;
function findPhrase(phraseId) {
if ((phraseId == null) || (phraseId == ""))
return null;
if ((languative.selectedDictionary != null) && (phraseId in languative.selectedDictionary))
return languative.selectedDictionary[phraseId];
if (phraseId in languative.dictonaries.html)
return languative.dictonaries.html[phraseId];
return null;
}
languative.findPhrase = findPhrase;
function getYesNo(value) {
if (value === undefined)
return getPhrase("undefined"); else if (value)
return getPhrase("yes"); else
return getPhrase("no");
}
languative.getYesNo = getYesNo;
function getAttr(node, attr) {
var result = (node.getAttribute && node.getAttribute(attr)) || null;
if (!result && node.attributes) {
for (var i = 0; i < node.attributes.length; i++) {
var attrNode = node.attributes[i];
if (attrNode.nodeName === attr)
return attrNode.nodeValue;
}
}
return result;
}
function getDictionaryFromHtml() {
function getNodeValue(node) {
var res = null;
if (node.tagName !== 'INPUT') {
if ("innerHTML" in node) {
res = node["innerHTML"];
} else {
res = node.nodeValue;
}
} else {
res = node.getAttribute("placeholder") || node.value;
}
if (res != null) {
res = res.replace(/\s{2,}/g, ' ');
res = res.replace(/^\s+|\s+$/g, '');
}
return res;
}
function getTagPhrase(tag) {
if (tag.childNodes.length > 1) {
var resPhrase = new Array();
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var chName = chNode.nodeName.toLowerCase();
var chValue = null;
if (chName in languative.ignoreTags)
chValue = languative.ignoreTags[chName]; else
chValue = getNodeValue(chNode);
resPhrase.push(chValue);
}
return resPhrase;
} else {
return getNodeValue(tag);
}
}
var tags = getHtmlTags();
var resDict = new Object();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = getTagPhrase(tag);
if ((phraseId in resDict) && (resDict[phraseId] != phraseValue)) {
console.warn("Different phrases with the same data-phrase-id='" + phraseId + "'\n" + " 1: " + JSON.stringify(resDict[phraseId], null, " ") + "\n 2: " + JSON.stringify(phraseValue, null, " "));
} else {
resDict[phraseId] = phraseValue;
}
}
}
return resDict;
}
languative.getDictionaryFromHtml = getDictionaryFromHtml;
function changeLanguage(langKey) {
function setTagPhrase(tag, phrase) {
if (tag.childNodes.length > 1) {
for (var ci = 0; ci < tag.childNodes.length; ci++) {
var chNode = tag.childNodes[ci];
var nName = chNode.nodeName.toLowerCase();
if (!(nName in languative.ignoreTags)) {
console.log(chNode.tagName)
if (chNode.tagType !== 'INPUT') {
if ("innerHTML" in chNode) {
chNode["innerHTML"] = " " + phrase[ci] + " ";
} else {
chNode.nodeValue = " " + phrase[ci] + " ";
}
} else {
chNode.hasAttribute("placeholder")
? chNode.setAttribute("placeholder", phrase[ci])
: chNode.value = phrase[ci];
}
}
}
} else {
if (tag.tagName !== 'INPUT') {
tag.innerHTML = " " + phrase + " ";
} else {
tag.hasAttribute("placeholder")
? tag.setAttribute("placeholder", phrase)
: tag.value = phrase;
}
}
}
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
console.warn("Cannot identify dictionary by key '" + langKey + "'. Default dictionary (" + languative.dictonaries.html._id + ": " + languative.dictonaries.html._name + ") used instead.");
langDict = languative.dictonaries.html;
}
languative.selectedDictionary = langDict;
var tags = getHtmlTags();
for (var ti = 0; ti < tags.length; ti++) {
var tag = tags[ti];
var phraseId = getAttr(tag, phraseIdAttr);
if ((phraseId != null)) {
var phraseValue = languative.getPhrase(phraseId);
if (phraseValue) {
setTagPhrase(tag, phraseValue);
} else {
console.warn("Phrase not definied in dictionary: data-phrase-id='" + phraseId + "'");
}
}
}
if (langDict["Title"] != null) {
document.title = langDict["Title"];
}
}
languative.changeLanguage = changeLanguage;
function getHtmlTags() {
var res = new Array();
var docTags = document.body.getElementsByTagName("*");
for (var i = 0; i < docTags.length; i++) {
var docTag = docTags[i];
var phraseId = getAttr(docTag, phraseIdAttr);
if (phraseId)
res.push(docTag);
}
return res;
}
var initialized = false;
function init() {
if (!initialized) {
initialized = true;
var htmlDict = languative.getDictionaryFromHtml();
for (var dictKey in htmlDict) {
if (!(dictKey in languative.dictonaries.html)) {
languative.dictonaries.html[dictKey] = htmlDict[dictKey];
}
}
var nav = window.navigator;
languative.changeLanguage(nav.userLanguage || nav.language);
}
}
languative.init = init;
function modifyDictionary(langKey, dictModifications) {
var langDict = languative.getDictionary(langKey);
if (langDict == null) {
languative.dictonaries[langKey.toLowerCase()] = dictModifications;
} else {
for (var dictKey in dictModifications) {
langDict[dictKey] = dictModifications[dictKey];
}
}
}
languative.modifyDictionary = modifyDictionary;
})(languative || (languative = {}));
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', languative.init);
if (window.addEventListener) {
window.addEventListener('load', languative.init, false);
} else {
window.attachEvent('onload', languative.init);
}
languative.modifyDictionary("ru", {
name: "Ваше имя",
email: "Ваш email",
send: "Отправить сообщение"
});
languative.modifyDictionary("de", {
name: "Ihr Name",
email: "Deine E-Mail",
send: "Nachricht senden"
});
ul li{
list-style: none;
}
<ul>
<li>English</li>
<li>Russian</li>
<li>German</li>
</ul>
<form>
<input type="text" name="name" data-phrase-id="name" placeholder="Your name">
<input type="text" name="email" data-phrase-id="email" placeholder="Your email">
<input type="submit" data-phrase-id="send" value="Send message">
</form>
I have an issue with a custom google script I'm making to generate a bunch of sheets with info based on other sheets. I can't figure out why this is happening..
I've tried including logs and the values before the return is correct.. however when its returned, I get the value undefined.
it's regarding the function: getTournamentInfo(), called from tournamentInfo = getTournamentInfo(matchInfo[0]);
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
tournaments.forEach(function (tournament) {
if (tournament != "")
{
var tInfo = sheet.getRange("B"+r+":K"+r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
});
}
function generateSheets() {
var sheet = ss.getSheetByName("Match Schedule");
var matches = sheet.getRange("B5:B").getValues().filter(String);
var r = 5;
matches.forEach(function (match) {
if (match != "")
{
var matchInfo = sheet.getRange("B"+r+":L"+r).getValues().toString().split(",");
if (matchInfo[10] == "true") // Checks wether or not to generate the sheet
{
console.log("Generate = " + matchInfo[10]);
console.log("Fetching Tournament Info: " + matchInfo);
var tournamentInfo = "";
try {
tournamentInfo = getTournamentInfo(matchInfo[0]);
} catch (e) {
console.log(e);
}
console.log(tournamentInfo);
var template = "1v1PlayerTemplate"; // Default Template
if (tournamentInfo[3] == 2) {
template = "1v1TeamTemplate";
} else if (tournamentInfo[3] == 3) {
template = "XvXTeamTaplte";
}
var sheetName = matchInfo[0] + " | " + matchInfo[1];
var matchSheet = ss.getSheetByName(template).copyTo(ss.getSheetByName(template).getParent()).setName(sheetName);
}
}
r++;
});
}```
Your getTournamentInfo function is not returning your result. Your return statement only short-circuits the function supplied in forEach. This is one of the possible solutions (untested):
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
let result; // <----
tournaments.forEach(function (tournament) {
if (tournament != "" && result == undefined) { // <-----
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
result = tInfo; // <----
}
}
});
return result; // <----
}
You can do it more simply with a for loop, instead of forEach:
function getTournamentInfo(abbreviation) {
var sheet = ss.getSheetByName("Tournaments");
var tournaments = sheet.getRange("B2:B").getValues().filter(String);
console.log("Fetching Abbreviation: " + abbreviation);
var r = 2;
for (const tournament of tournaments) { // <==============
if (tournament != "") {
var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
if (tInfo[0] == abbreviation) {
console.log("Returning Info for: " + tInfo[0]);
return tInfo;
}
}
}
}
On a MouseEvent instance, we have a property called path, it might look like this:
Does anybody know if there is a reliable way to translate this path array into an XPath? I assume that this path data is the best data to start from? Is there a library I can use to do the conversion?
This library looks promising, but it doesn't use the path property of an event: https://github.com/johannhof/xpath-dom
There's not a unique XPath to a node, so you'll have to decide what's the most appropriate way of constructing a path. Use IDs where available? Numeral position in the document? Position relative to other elements?
See getPathTo() in this answer for one possible approach.
PS: Taken from Javascript get XPath of a node
Another option is to use SelectorGadget from below link
https://dv0akt2986vzh.cloudfront.net/unstable/lib/selectorgadget.js
The actual code for the DOM path is at
https://dv0akt2986vzh.cloudfront.net/stable/lib/dom.js
Usage: on http://google.com
elem = document.getElementById("q")
predict = new DomPredictionHelper()
predict.pathOf(elem)
// gives "body.default-theme.des-mat:nth-child(2) div#_Alw:nth-child(4) form#f:nth-child(2) div#fkbx:nth-child(2) input#q:nth-child(2)"
predict.predictCss([elem],[])
// gives "#q"
CODE if link goes down
// Copyright (c) 2008, 2009 Andrew Cantino
// Copyright (c) 2008, 2009 Kyle Maxwell
function DomPredictionHelper() {};
DomPredictionHelper.prototype = new Object();
DomPredictionHelper.prototype.recursiveNodes = function(e){
var n;
if(e.nodeName && e.parentNode && e != document.body) {
n = this.recursiveNodes(e.parentNode);
} else {
n = new Array();
}
n.push(e);
return n;
};
DomPredictionHelper.prototype.escapeCssNames = function(name) {
if (name) {
try {
return name.replace(/\s*sg_\w+\s*/g, '').replace(/\\/g, '\\\\').
replace(/\./g, '\\.').replace(/#/g, '\\#').replace(/\>/g, '\\>').replace(/\,/g, '\\,').replace(/\:/g, '\\:');
} catch(e) {
console.log('---');
console.log("exception in escapeCssNames");
console.log(name);
console.log('---');
return '';
}
} else {
return '';
}
};
DomPredictionHelper.prototype.childElemNumber = function(elem) {
var count = 0;
while (elem.previousSibling && (elem = elem.previousSibling)) {
if (elem.nodeType == 1) count++;
}
return count;
};
DomPredictionHelper.prototype.pathOf = function(elem){
var nodes = this.recursiveNodes(elem);
var self = this;
var path = "";
for(var i = 0; i < nodes.length; i++) {
var e = nodes[i];
if (e) {
path += e.nodeName.toLowerCase();
var escaped = e.id && self.escapeCssNames(new String(e.id));
if(escaped && escaped.length > 0) path += '#' + escaped;
if(e.className) {
jQuery.each(e.className.split(/ /), function() {
var escaped = self.escapeCssNames(this);
if (this && escaped.length > 0) {
path += '.' + escaped;
}
});
}
path += ':nth-child(' + (self.childElemNumber(e) + 1) + ')';
path += ' '
}
}
if (path.charAt(path.length - 1) == ' ') path = path.substring(0, path.length - 1);
return path;
};
DomPredictionHelper.prototype.commonCss = function(array) {
try {
var dmp = new diff_match_patch();
} catch(e) {
throw "Please include the diff_match_patch library.";
}
if (typeof array == 'undefined' || array.length == 0) return '';
var existing_tokens = {};
var encoded_css_array = this.encodeCssForDiff(array, existing_tokens);
var collective_common = encoded_css_array.pop();
jQuery.each(encoded_css_array, function(e) {
var diff = dmp.diff_main(collective_common, this);
collective_common = '';
jQuery.each(diff, function() {
if (this[0] == 0) collective_common += this[1];
});
});
return this.decodeCss(collective_common, existing_tokens);
};
DomPredictionHelper.prototype.tokenizeCss = function(css_string) {
var skip = false;
var word = '';
var tokens = [];
var css_string = css_string.replace(/,/, ' , ').replace(/\s+/g, ' ');
var length = css_string.length;
var c = '';
for (var i = 0; i < length; i++){
c = css_string[i];
if (skip) {
skip = false;
} else if (c == '\\') {
skip = true;
} else if (c == '.' || c == ' ' || c == '#' || c == '>' || c == ':' || c == ',') {
if (word.length > 0) tokens.push(word);
word = '';
}
word += c;
if (c == ' ' || c == ',') {
tokens.push(word);
word = '';
}
}
if (word.length > 0) tokens.push(word);
return tokens;
};
DomPredictionHelper.prototype.decodeCss = function(string, existing_tokens) {
var inverted = this.invertObject(existing_tokens);
var out = '';
jQuery.each(string.split(''), function() {
out += inverted[this];
});
return this.cleanCss(out);
};
// Encode css paths for diff using unicode codepoints to allow for a large number of tokens.
DomPredictionHelper.prototype.encodeCssForDiff = function(strings, existing_tokens) {
var codepoint = 50;
var self = this;
var strings_out = [];
jQuery.each(strings, function() {
var out = new String();
jQuery.each(self.tokenizeCss(this), function() {
if (!existing_tokens[this]) {
existing_tokens[this] = String.fromCharCode(codepoint++);
}
out += existing_tokens[this];
});
strings_out.push(out);
});
return strings_out;
};
DomPredictionHelper.prototype.simplifyCss = function(css, selected_paths, rejected_paths) {
var self = this;
var parts = self.tokenizeCss(css);
var best_so_far = "";
if (self.selectorGets('all', selected_paths, css) && self.selectorGets('none', rejected_paths, css)) best_so_far = css;
for (var pass = 0; pass < 4; pass++) {
for (var part = 0; part < parts.length; part++) {
var first = parts[part].substring(0,1);
if (self.wouldLeaveFreeFloatingNthChild(parts, part)) continue;
if ((pass == 0 && first == ':') || // :nth-child
(pass == 1 && first != ':' && first != '.' && first != '#' && first != ' ') || // elem, etc.
(pass == 2 && first == '.') || // classes
(pass == 3 && first == '#')) // ids
{
var tmp = parts[part];
parts[part] = '';
var selector = self.cleanCss(parts.join(''));
if (selector == '') {
parts[part] = tmp;
continue;
}
if (self.selectorGets('all', selected_paths, selector) && self.selectorGets('none', rejected_paths, selector)) {
best_so_far = selector;
} else {
parts[part] = tmp;
}
}
}
}
return self.cleanCss(best_so_far);
};
DomPredictionHelper.prototype.wouldLeaveFreeFloatingNthChild = function(parts, part) {
return (((part - 1 >= 0 && parts[part - 1].substring(0, 1) == ':') &&
(part - 2 < 0 || parts[part - 2] == ' ') &&
(part + 1 >= parts.length || parts[part + 1] == ' ')) ||
((part + 1 < parts.length && parts[part + 1].substring(0, 1) == ':') &&
(part + 2 >= parts.length || parts[part + 2] == ' ') &&
(part - 1 < 0 || parts[part - 1] == ' ')));
};
DomPredictionHelper.prototype.cleanCss = function(css) {
return css.replace(/\>/, ' > ').replace(/,/, ' , ').replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '').replace(/,$/, '');
};
DomPredictionHelper.prototype.getPathsFor = function(arr) {
var self = this;
var out = [];
jQuery.each(arr, function() {
if (this && this.nodeName) {
out.push(self.pathOf(this));
}
})
return out;
};
DomPredictionHelper.prototype.predictCss = function(s, r) {
var self = this;
if (s.length == 0) return '';
var selected_paths = self.getPathsFor(s);
var rejected_paths = self.getPathsFor(r);
var css = self.commonCss(selected_paths);
var simplest = self.simplifyCss(css, selected_paths, rejected_paths);
// Do we get off easy?
if (simplest.length > 0) return simplest;
// Okay, then make a union and possibly try to reduce subsets.
var union = '';
jQuery.each(s, function() {
union = self.pathOf(this) + ", " + union;
});
union = self.cleanCss(union);
return self.simplifyCss(union, selected_paths, rejected_paths);
};
DomPredictionHelper.prototype.fragmentSelector = function(selector) {
var self = this;
var out = [];
jQuery.each(selector.split(/\,/), function() {
var out2 = [];
jQuery.each(self.cleanCss(this).split(/\s+/), function() {
out2.push(self.tokenizeCss(this));
});
out.push(out2);
});
return out;
};
// Everything in the first selector must be present in the second.
DomPredictionHelper.prototype.selectorBlockMatchesSelectorBlock = function(selector_block1, selector_block2) {
for (var j = 0; j < selector_block1.length; j++) {
if (jQuery.inArray(selector_block1[j], selector_block2) == -1) {
return false;
}
}
return true;
};
// Assumes list is an array of complete CSS selectors represented as strings.
DomPredictionHelper.prototype.selectorGets = function(type, list, the_selector) {
var self = this;
var result = true;
if (list.length == 0 && type == 'all') return false;
if (list.length == 0 && type == 'none') return true;
var selectors = self.fragmentSelector(the_selector);
var cleaned_list = [];
jQuery.each(list, function() {
cleaned_list.push(self.fragmentSelector(this)[0]);
});
jQuery.each(selectors, function() {
if (!result) return;
var selector = this;
jQuery.each(cleaned_list, function(pos) {
if (!result || this == '') return;
if (self._selectorGets(this, selector)) {
if (type == 'none') result = false;
cleaned_list[pos] = '';
}
});
});
if (type == 'all' && cleaned_list.join('').length > 0) { // Some candidates didn't get matched.
result = false;
}
return result;
};
DomPredictionHelper.prototype._selectorGets = function(candidate_as_blocks, selector_as_blocks) {
var cannot_match = false;
var position = candidate_as_blocks.length - 1;
for (var i = selector_as_blocks.length - 1; i > -1; i--) {
if (cannot_match) break;
if (i == selector_as_blocks.length - 1) { // First element on right.
// If we don't match the first element, we cannot match.
if (!this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position])) cannot_match = true;
position--;
} else {
var found = false;
while (position > -1 && !found) {
found = this.selectorBlockMatchesSelectorBlock(selector_as_blocks[i], candidate_as_blocks[position]);
position--;
}
if (!found) cannot_match = true;
}
}
return !cannot_match;
};
DomPredictionHelper.prototype.invertObject = function(object) {
var new_object = {};
jQuery.each(object, function(key, value) {
new_object[value] = key;
});
return new_object;
};
DomPredictionHelper.prototype.cssToXPath = function(css_string) {
var tokens = this.tokenizeCss(css_string);
if (tokens[0] && tokens[0] == ' ') tokens.splice(0, 1);
if (tokens[tokens.length - 1] && tokens[tokens.length - 1] == ' ') tokens.splice(tokens.length - 1, 1);
var css_block = [];
var out = "";
for(var i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ') {
out += this.cssToXPathBlockHelper(css_block);
css_block = [];
} else {
css_block.push(tokens[i]);
}
}
return out + this.cssToXPathBlockHelper(css_block);
};
// Process a block (html entity, class(es), id, :nth-child()) of css
DomPredictionHelper.prototype.cssToXPathBlockHelper = function(css_block) {
if (css_block.length == 0) return '//';
var out = '//';
var first = css_block[0].substring(0,1);
if (first == ',') return " | ";
if (jQuery.inArray(first, [':', '#', '.']) != -1) {
out += '*';
}
var expressions = [];
var re = null;
for(var i = 0; i < css_block.length; i++) {
var current = css_block[i];
first = current.substring(0,1);
var rest = current.substring(1);
if (first == ':') {
// We only support :nth-child(n) at the moment.
if (re = rest.match(/^nth-child\((\d+)\)$/))
expressions.push('(((count(preceding-sibling::*) + 1) = ' + re[1] + ') and parent::*)');
} else if (first == '.') {
expressions.push('contains(concat( " ", #class, " " ), concat( " ", "' + rest + '", " " ))');
} else if (first == '#') {
expressions.push('(#id = "' + rest + '")');
} else if (first == ',') {
} else {
out += current;
}
}
if (expressions.length > 0) out += '[';
for (var i = 0; i < expressions.length; i++) {
out += expressions[i];
if (i < expressions.length - 1) out += ' and ';
}
if (expressions.length > 0) out += ']';
return out;
};
I want to know how to store dynamic array of objects in LocalStorage and display it in table format on the page.
I also want to perform update and delete operation on particular item. How can i do this?
I have tried this:
var _local = (function () {
var Person = {
Srno: 0,
Name: "",
Birthdate: "",
Email: "",
Address: "",
Contact: "",
};
this.clearuielements = function () {
var inputs = document.getElementsByClassName("c1");
for (i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
}
this.saveitem = function() {
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("c1");
nameVal();
console.log("aaaaaaaaaaaaaaaa");
Person.Srno = inputs[0].value;
Person.Name = inputs[1].value;
Person.Birthdate = inputs[2].value;
Person.Email = inputs[3].value;
Person.Address = inputs[4].value;
Person.Contact = inputs[5].value;
localStorage.setItem("Person_" + lscount, JSON.stringify(Person));
location.reload();
}
function loaddata() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";
for (i = 0; i < datacount; i++) {
var key = localStorage.key(i);
var person = localStorage.getItem(key);
var data = JSON.parse(person);
render += "<tr><td>" + data.Srno + "</td><td>" + data.Name + " </td>";
render += "<td>" + data.Birthdate + "</td>";
render += "<td>" + data.Email + "</td>";
render += "<td>" + data.Address + "</td>";
render += "<td>" + data.Contact + "</td></tr>";
}
render+="</table>";
dvcontainer.innerHTML = render;
}
}
this.clearstorage = function() {
localStorage.clear();
window.location.reload();
}
function nameVal() {
document.getElementById("txtpname").focus();
var n=document.getElementById("txtpname").value;
var r;
var letters = /^[a-zA-Z]+$/;
if(n==null||n==""){
alert("please enter user name");
return null;
n.focus();
}
else {
if(n.match(letters)&&n!="") {
r=ValidateEmail();
return r;
}
else {
alert("please enter alphabates");
document.getElementById("txtpname").value="";
document.getElementById("txtpname").focus();
return null;
}
}
}
function ValidateEmail()
{
var uemail=document.getElementById("txtpemail").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.match(mailformat)) {
alphanumeric();
}
else {
alert("You have entered an invalid email address!");
document.getElementById("txtpemail").value="";
document.getElementById("txtpemail").focus();
return null;
}
}
function alphanumeric()
{
var uadd=document.getElementById("txtpaddr").value;
var letters = /^[0-9a-zA-Z]+$/;
if(uadd==null||uadd==""){
alert("plz enter address");
uadd.focus();
}
else {
if(uadd.match(letters)) {
return true;
}
else {
alert('User address must have alphanumeric characters only');
document.getElementById("txtpaddr").value="";
document.getElementById("txtpaddr").focus();
return false;
}
}
}
function cntVal(){
var n=document.getElementById("txtpmobile").value;
var r1;
var letters = /^\d{10}$/;
if(n!==null||n!==""){
if(n.match(letters))
{
r1=ValidateEmail();
return r1;
}
else {
alert("please enter contact number");
document.getElementById("txtpmobile").value="";
document.getElementById("txtpmobile").focus();
return null;
}
}
else {
alert("please enter contact Number");
return null;
n.focus();
}
}
return this;
window.onload = function () {
loaddata();
};
})();
function saveitem(){
console.log("SSSSS",_local);
_local.saveitem();
}
function clearstorage(){
_local.clearstorage();
}
function clearuielements(){
_local.clearuielements();
}
I've tried this a thousand different ways in a thousand different times and my JS code won't come out the way I want it. When I run it in the Mozilla scratchpad, I get "userHand is undefined" and the second printHand shows as undefined, too. Could someone show me where are the errors in my blackjack game?
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
cards.push(deal());
cards.push(deal());
this.getHand = function () {
return cards;
};
this.score = function () {
var score;
for (i = 0; i < cards.length; i++) {
score = score + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (score > 21 && cards[i].getValue() === 11) {
score = score - 10;
}
} return score;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} alert(hand);
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
};
var playAsUser = function () {
var playUser = new Hand();
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
return "You lose.";
} else if (userHand.score > dealerHand.score) {
return "You win.";
} else {
return "You tied.";
}
};
var playGame = function () {
var user = playAsUser();
var dealer = playAsDealer();
declareWinner(user, dealer);
console.log("User got " + user.printHand());
console.log("Dealer got " + dealer.printHand());
};
playGame();
You aren't returning nothing on printHand()
I just added the return statement and worked. See this fiddle
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
}
//alert(hand); //remove this alert
return hand; // <----- solution
};