Need some improvement in xml display - javascript

i have implemented this code to display xml in html using javascript
current output
Need something like
Here is my code
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
var f = false;
if (n.nodeType !== 3) {
str += '<br><<span class="nn">' + n.nodeName + '</span>>';
if (n.hasChildNodes()) {
f = true;
str += parseXML(n, s++);
}
str += '</<span class="nn">' + n.nodeName + '</span>>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
if (f) {
str += '<br>';
}
}
var str = str.replace(/(<br>)+/g, '<br>');
return str;
}
how i call this
R : xml object
s : initial 0 (i am passing this so that i can display xml as hirarchical view)
Output in second
- is not required
i have post second out as it can be seen while opening xml document in firefox
please ask if any doubt

I solved it myself.
Updated code with the solution
var pre = 0;
function parseXML(R, s) {
var C = R.childNodes;
var str = '';
for (var i = 0; i < C.length; i++) {
var n = C[i];
if (n.nodeType !== 3) {
str += '<br>' + gs(s) + '<b><</b><span class="nn">' + n.nodeName + '</span><b>></b>';
if (n.hasChildNodes()) {
str += parseXML(n, s + 1);
}
if (pre !== 3) {
str += '<br>' + gs(s);
}
str += '<b><</b>/<span class="nn">' + n.nodeName + '</span><b>></b>';
} else {
str += '<span class="nv">' + n.nodeValue + '</span>';
}
pre = n.nodeType;
}
return str;
}

Related

create function hollow square in javascript

i want to create hollow square with function in javascript.
this my code
let test = num => {
var edge = '*';
var inside = ' ';
var printline;
for (var i = 1; i <= num; i++) {
if (i === 1 || i === num) {
printline = Array(num + 1).join(edge);
} else {
printline = edge + Array(num - 1).join(inside) + edge;
}
}
return printline;
}
console.log(test(4));
currently output is
****
but i want my output like this
****
* *
* *
****
You should reuse printline, not overwrite it.
Also, it needs the new line and carriage return (\r\n) on every iteration
let test = num => {
var edge = '*';
var inside = ' ';
var printline='';
for (var i = 1; i <= num; i++) {
if (i === 1 || i === num) {
printline += Array(num + 1).join(edge);
} else {
printline += edge + Array(num - 1).join(inside) + edge;
}
printline+='\r\n';
}
return printline;
}
console.log(test(4));
please update the lines of codes below.
var printline = '';
printline += Array(num + 1).join(edge) + '\n';
printline += edge + Array(num - 1).join(inside) + edge + '\n';

Removing random element from an array /Javascript

I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.
You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.
Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);
You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}
#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));
Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}

Convert numbers to arabic letters in JavaScript

Below is my code, when I try to convert 23, it converted to عشرين تلاته, but I want it converted to ثلاثة وعشرون وهكذا.
var th = ['', 'ألف', 'مليون', 'مليار', 'تريليون'];
var dg = ['صفر', 'واحد', 'اثنين', 'ثلاثة', 'أربعة', 'خمسة', 'ستة', 'سبعة', 'ثمانية', 'تسعة'];
var tn = ['عشرة', 'أحد عشر', 'اثني عشر', 'ثلاثة عشر', 'أربعة عشر', 'خمسة عشر', 'ستة عشر', 'سبعة عشر', 'ثمانية عشر', 'تسعة عشر'];
var tw = ['عشرون', 'ثلاثون', 'الأربعين', 'خمسين', 'ستين', 'السبعين', 'ثمانين', 'تسعين'];
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g, '');
if (s != parseFloat(s)) return 'لیس عدد';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15) return 'كبير جدا';
var n = s.split('');
var str = '';
var sk = 0;
for (var i = 0; i < x; i++) {
if ((x - i) % 3 == 2) {
if (n[i] == '1') {
str += tn[Number(n[i + 1])] + ' ';
i++;
sk = 1;
} else if (n[i] != 0) {
str += tw[n[i] - 2] + ' ';
sk = 1;
}
} else if (n[i] != 0) {
str += dg[n[i]] + ' ';
if ((x - i) % 3 == 0) str += 'مائة ';
sk = 1;
}
if ((x - i) % 3 == 1) {
if (sk) str += th[(x - i - 1) / 3] + ' ';
sk = 0;
}
}
if (x != s.length) {
var y = s.length;
str += 'نقطة ';
for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
}
return str.replace(/\s+/g, ' ');
}
console.log(toWords(23))
var th = ['', 'ألف', 'مليون', 'مليار', 'تريليون'];
var dg = ['صفر', 'واحد', 'اثنين', 'ثلاثة', 'أربعة', 'خمسة', 'ستة', 'سبعة', 'ثمانية', 'تسعة'];
var tn = ['عشرة', 'أحد عشر', 'اثني عشر', 'ثلاثة عشر', 'أربعة عشر', 'خمسة عشر', 'ستة عشر', 'سبعة عشر', 'ثمانية عشر', 'تسعة عشر'];
var tw = ['عشرون', 'ثلاثون', 'الأربعين', 'خمسين', 'ستين', 'السبعين', 'ثمانين', 'تسعين'];
//console.log(th);
function toWords(s) {
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s)) return 'ليس رقم';
var x = s.indexOf('.');
if (x == -1)
x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++) {
if ((x-i)%3==2) {
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' '+ ' ';
i++;
sk=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + ' ';
sk=1;
}
} else if (n[i]!=0) { // 0235
str = dg[n[i]] + ' ' + str + ' ';
if ((x-i)%3==0) str += 'مائة و ';
sk=1;
}
if ((x-i)%3==1) {
if (sk)
str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
if (x != s.length) {
var y = s.length;
str += 'point ';
for (var i=x+1; i<y; i++)
str += dg[n[i]] +' ';
}
return str.replace(/\s+/g,' ');
}
console.log("23 : "+ toWords(23));
console.log("120: "+ toWords(120));
Hi I don't understand Arabic but I guess the solution to this can be find in this particular question/solution.
Convert digits into words with JavaScript

Internet Explorer gives error: ')' is expected, while firefox isn't?

Internet Explorer gives an error ')' is expected while Firefox is running this code fine. According to the Internet Explorer console the error is situated in the first line:
function HTMLtableRows (titles=[] , values=[]) {
How can I fix this problem?
function HTMLtableRows (titles=[] , values=[]) {
var i, j;
var str, strT, strM;
str = '<table class="table">';
str = str + '<tr>';
for (j = 0; j < titles.length; j++) {
str = str + '<th colspan="2"><center>' + titles[j] + '</center></th>';
}
str = str + '</tr>' + '<tr>';
for (j = 0; j < titles.length; j++) {
str = str + '<th>Tijdstip</th>' + '<th>Looptijd</th>';
}
str = str + '</tr>' + '<tr>';
for (j = 0; j < titles.length; j++) {
var a = values[j].split('\r');
strT = ''
strM = ''
for (i = 0; i < a.length; i++) {
var b = a[i].split('=');
if (b[1] != undefined) {
strT = strT + b[0];
strM = strM + b[1] + 'min';
}
if (i < a.length - 1) {
strT = strT + '<br>';
strM = strM + '<br>';
}
}
str = str + '<td>' + strT + '</td>';
str = str + '<td>' + strM + '</td>';
}
str = str + '</tr>';
str = str + '</table>';
return str;
}
IE does not support default parameters.
Just do it like this if you want
function HTMLtableRows (titles , values) {
if (!titles) titles = [];
if (!values) values = [];
console.log(titles);
console.log(values);
}
a1 = [1,2,3];
HTMLtableRows(a1, null);
HTMLtableRows({foo: "bar"}, undefined);
HTMLtableRows(2, NaN);
HTMLtableRows("not empty string", "");
HTMLtableRows(1, 0);
HTMLtableRows(true, false);
All of the following values
null
undefined
NaN
""
0
false
will become an empty array. If you don't want some of those values to be overwritten with an empty array adjust if conditions as you see fit.
Example where you allow values to remain unchanged as "", 0 and NaN:
function HTMLtableRows (titles , values) {
if (!titles) titles = [];
if(values != "" &&
values != 0 &&
!isNaN(parseInt(values))
)
values = [];
console.log(titles);
console.log(values);
}
HTMLtableRows("string", "");
HTMLtableRows(1, 0);
HTMLtableRows(7, NaN);
Thanks to alex i've solved this with the adjustments below:
function HTMLtableRows (tmpTitles , tmpValues) {
titles=[];
values=[];
titles = tmpTitles;
values = tmpValues;
//...
}

change the text of a label and in js and use it from code behind?

I created a list of buttons from code behind, and append them on some div, how ever each button has an onclick java script function
here is how I did it:
string[] messages = CM.GetMessages(Session["USER_EMAIL"].ToString()).Split(new string[] { "$STARTCHAT$" }, StringSplitOptions.None);
string[] usersalone = CM.GetChaters(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
string[] username = CM.GetUserNames(Session["USER_EMAIL"].ToString()).Split(new string[] { "$NEWUSER$" }, StringSplitOptions.None);
for (int i = messages.Length-2; i>=0; i--)
{
Button b = new Button();
b.ID = Session["USER_EMAIL"].ToString()+username[i];
b.Text = "Chat With: " + usersalone[i] ;
b.Width = 250;
b.Height = 100;
b.OnClientClick = "return DisplayMessage('" + messages[i+1] + "','" + username[i] + "','" + Session["USER_EMAIL"].ToString() + "')";
b.Style.Add("background-color", "rgb(246, 246, 246)");
// lblChatwith.Text = username[i];
NewMsgNotArrow.Controls.Add(b);
}
and here is my java script function:
function DisplayMessage(messages, from, username) {
document.getElementById("AllMessages").innerText ="";
document.getElementById("DivDisplayMessage").style.visibility = "visible";
document.getElementById("lblChatwith").innerText = from;
var MessageForEachUser = messages.split("$SAMECHATNEWTEXT$");
for (var i = 0; i < MessageForEachUser.length; i++)
{
var ck = MessageForEachUser[i].indexOf("$" + from.toUpperCase() + "$") > -1;
if (ck == true) {
document.getElementById("AllMessages").innerText += from.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + from.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
if (ck == false) {
document.getElementById("AllMessages").innerText += username.toUpperCase() + ":\n";
var temp = MessageForEachUser[i].split("$" + username.toUpperCase() + "$");
MessageForEachUser[i] = temp[0];
}
document.getElementById("AllMessages").innerText += MessageForEachUser[i] + "\n______________________________________________________" + "\n";
}
return false;
}
every thing is working well but, when i want to use one of the labels like "lblchatwith" from code behind it return an empty string.

Categories