adding line breaks to array values javascript - javascript

Here is my javascript array:
var quizArray = [
'When the weather is agreeable what do you prefer to do the most?~Something outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~','It\'s a weeknight and friend invites you to an orchestra. You would?~Kindly refuse. It\'s just not my thing.~Go, unquestionably. I love all art forms.~Ask who the composer is, then read all about them before going.~Confuse Orchestra with Opera and begin singing in Latin.~Go if the tickets are free, otherwise no.~~~',]
When I load my html it won't display line breaks after each answer. I've tried adding a .join(<\br>) after split, but that breaks up every single word, here is the code I have:
function displayQuiz(ent, qnum) {
perPage++;
var qna = quizArray[qnum].split('~');
var od = []; for (var i = 1; qna[i] != null && qna[i] != ''; i++) od.push(i); od.sort( randOrd ); od.sort( randOrd );
var newF = document.createElement("form");
var newDq = document.createElement("div");
newDq.className = 'question';
newDq.appendChild(document.createTextNode(Number(qnum+1)+ ': ' +qna[0]));
newF.appendChild(newDq);
newDq = document.createElement("div");
newDq.className = 'answers';
for (var i = 1; qna[i] != null && qna[i] != ''; i++) {var newDa = document.createElement("label"); newDa.htmlFor = 'a'+qnum+i; /*#cc_on #if (#_jscript) var newR = document.createElement("<input name='a"+qnum+"'>"); #else */
var newR = document.createElement("input");
newR.name = 'a'+qnum; /* #end #*/
newR.type = 'radio';
newR.id = 'a'+qnum+i;
newR.value = od[i-1];
newDa.appendChild(newR);
newDa.appendChild(document.createTextNode(' '+qna[od[i-1]]+' '));
newDq.appendChild(newDa);}
newF.appendChild(newDq);
document.getElementById('quiz'+perPage).appendChild(newF);
}
I'll try my best to post additional info if needed. I did use this as a snippet and am very novice on Javascript. Not opposed to learning on my own but I've poured over the interwebs and cannot find my answer.

to make an array of Strings its better if you put your complete string in a var and after make a split(), and for add you can use a join() or a for()
It's better put this way the code
var quizArray = 'When the weather is agreeable what do you prefer to do the most?~Something outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~';
function displayQuiz(ent, qnum) {
perPage++;
var qna = quizArray.split('~');
var res = qna.join(" <br> ");
return res;
}

Here is the approach that I took, using .join to add the br element. I think you weren't specifying what to split on originally, if it added br after every word.
var string = 'When the weather is agreeable what do you prefer to do the most?~Something
outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~';
var quizArray = string.split('~');
var finalString = quizArray.join('<br/>');
document.getElementById('yourIdHere').innerHTML = finalString;
Here's a fiddle: http://jsfiddle.net/brettwlutz/Q35J2/1/

i thought arrays were made as so:
var arr = [val1, val2, val3];
you can use arr.push to append more values or arr.unshift to add values to the beginning of the array
http://jsfiddle.net/h_awk/K3kEv/
<script>
var arr = [1, 2, 3, 4], i;
for( i=0; i<arr.length; i++ )
{
document.write(arr[i] + '<br />');
}
</script>

First, to answer your question. The above code should work and make the variable qna contain the new, split array. Your solution of adding .join("") should then turn that new array into a single string with html newlines. That is, unless you want t JS newline, in which case you should instead use .join("\n").
My question for you is, why are you starting with an array with only one element? A string can be split into an array and joined back into a string the same way. Also, it may be easier to, instead of using the tilde ~ to seperate the statements you want to split, just use a form of proper array syntax, then get rid of the "split" and just use the joining:
var quizArray = ["When the weather is agreeable what do you prefer to do the most?", "Something outside...Obviously!, I tend to enjoy things that aren\'t dependent on weather.", "Read, possibly outside if I can find my sunscreen.", "Do what I always do, which is whatever I want.", "Try something new, like Planking."];
My only possible understanding is that you are still learning JS and this is just an example for learning how to split arrays, but this is not really a real-life application, which is why this post seems questionable to Stack Overflow users.

Related

showing selected names in a <div> by using a javascript array

I have a div which displays name of the people who are online, I have the following members in
the div
<div id="members">
<span>Amlan Karmakar</span>
<span>Atin Roy</span>
<span>Arpan Burman</span>
<span>Ramanuj Mukherjee</span>
</div>
I have another javascript array friends[], which has 'Amlan Karmakar' and 'Ramanuj Mukherjee' has friends, I want to display those members who are in the friends[] array, I am inserting the name of the friends by friends.push("Amlan Karmakar"). The names in div are auto generated by cometd chat, I have written the names in the div for simplicity. I hope there is a solution to this problem. My previous question didn't solve my problem.
You could try something like the below, i.e. split the HTML of the div containing the members, loop through them and check if they are in the friendsArray. Note that this is a rough implementation, and that it assumes a reasonably new browser as it uses Ecmascript 5 features. The concept can applied using old-fashioned for loops too.
var all = document.getElementById('members').getElementsByTagName('span');
var friendsOnly = '';
for(var i=0; i<all.length; i++){
if(friendsArray.some(function(friend){
return friend == all[i].innerHTML;
})){
friendsOnly += '<span>' + all[i].innerHTML + '</span>';
}
});
all.innerHTML(friendsOnly);
By the way, I'm assuming the friendsArray may contain people who are not already in the div. If that is not the case, then I'm not sure what the question is about.
So you want to put the data from the friends[] array into the <div id="members">
I want only those names to show in the which are there in the friends[] array
If you only want to display the names which are in the friends array, as you suggested in your comment, I suppose this will do the trick:
var target = document.getElementById("members");
// Remove this line if you want to keep the current names in the members div.
target.innerHTML = ""; // Clean before inserting friends
for (var i = 0; i <= friends.length; i++) {
target.innerHTML += friends[i] + "<br />"; // Add friend + break
}
Try this to get only the friends out of the list of members:
var friendMembers = document.getElementById('members').split(/<br\s*[\/]?>/gi)
.filter(function(member) { return (friends.indexOf(member) > -1) } );
You should try knockout.js, this framework will help you handle this case.

how to load two dimensional array in javascript

I have a string containing many lines of the following format:
<word1><101>
<word2><102>
<word3><103>
I know how to load each line into an array cell using this:
var arrayOfStuff = stringOfStuff.split("\n");
But the above makes one array cell per line, I need a two-dimensional array.
Is there a way to do that using similar logic to the above without having to re-read and re-process the array. I know how to do it in two phases, but would rather do it all in one step.
Thanks in advance,
Cliff
It sounds like you're hoping for something like Python's list comprehension (e.g. [line.split(" ") for line in lines.split("\n")]), but Javascript has no such feature. The very simplest way to get the same result in Javascript is to use a loop:
var lines = lines.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = lines[i].split(" ");
// or alternatively, something more complex using regexes:
var match = /<([^>]+)><([^>]+)>/.exec(lines[i]);
lines[i] = [match[1], match[2]];
}
Not really. There are no native javascript functions that return a two-dimensional array.
If you wanted to parse a CSV for example, you can do
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n') // Normalize newlines
// Parse lines and dump them in parsedStuff.
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
Running
stringOfStuff = 'foo,bar\n\nbaz,boo,boo'
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n')
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
JSON.stringify(parsedStuff);
outputs
[["foo","bar"],[],["baz","boo","boo"]]
You can adjust the /,/ to suite whatever record separator you use.

Javascript Split properties into Object exclude inside Strings

What is the best method for splitting or extracting the css properties out of as string and into an object?
var cssProperties = 'background:green;content:"Content;";color:pink;';
The above should result in the following
var theObject = {
background:'green',
content:'"Content;"',
color:'pink'
}
Unfortunately I can not just use a split(";") and cycle through the array due to the semicolon in the url. I could create a giant loop that cycles through every character while skipping the ";" only while wrapped in quotes, but that seems kinda of wrong.
Is there a regex trick for this?
Optional:
Also are there any really good regex websites. I understand most of the syntax but there doesn't seem to be many practical really complicated examples on most of the websites I have found.
Here is a fiddle further demonstrating the function: http://jsfiddle.net/ZcEUL/
(function() {
var div = document.createElement('div'),
rprops =/[\w-]+(?=:)/g,
rcamelCase = /-(\D)/g,
fcamelCase = function(a,letter) {
return letter.toUpperCase();
};
window['styleToObject'] = function(str) {
var props = str.match(rprops),
prop, i = 0,
theObject = {};
div.style.cssText = str;
while (prop = props[i++]) {
var style=div.style[prop.replace(rcamelCase,fcamelCase)];
if (style) {
theObject[prop] = style;
}
}
return theObject;
};
})();
Here was the solution I made regarding your first css string you had listed... Not the best but maybe it'll help spark some ideas.
JSFiddle Example
Try this or something similar
var newString = cssProperties
.replace(":", ":'")
.replace(";", ", '");
var obj = eval(newString);

Why is wrap ignoring the last wrap?

I'm trying to turn more into a hyperlink, but it's like it totally ignores the last wrap.
$j('#sub > div[id^="post-"]').each(function() {
var sid=this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
$j(this).html(sfimg);
$j(sfimg).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).append(sfhh).append(sfpt);
$j(sfpt).wrap($j('<div>').attr('class', 'sfentry'));
$j(this).append('<div class="morelink">'+more+'</div>');
$j(more).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
You over-using the jquery function ($j(), in your case) and your doing things in the wrong order. Also, there may be cases (possibly) that $(this).find('img'), for instance, might return more than one element... Not sure of your scenario, though.
Try this (may not be perfect, but it should lean you in the right direction):
$j('#sub > div[id^="post-"]').each(function() {
var sid = this.id.match(/^post-([0-9]+)$/);
var sfimg = $j(this).find("img");
var sfhh = $j(this).find("h2");
var sfpt = $j(this).find("p:not(:has(img)):eq(0)");
var more = 'more';
sfimg.wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
$j(this).html(sfimg);
sfpt.wrap($j('<div>').attr('class', 'sfentry'));
// You do realize what you have will append the paragraph to your h2 tag, right?
// I think you want:
/*
$j(this).append(sfhh).end().append(sfpt);
*/
$j(this).append(sfhh).append(sfpt);
$j(this).append('<div class="morelink">'+more+'</div>');
$j('.morelink',this).wrap($j('<a>').attr('href', '/blog/?p='+sid[1]));
});
There were all sorts of crazy things going on in that code. Remember that you need to modify the objects before appending them to another object (unless you have some unique way of identifying them after the fact, i.e. IDs).
Good luck.
Why do you expect $j(more) to match anything?

How to do multiple regular expressions, each time refining the results?

Why can't I output my regex to a variable, and then run regex on it a second time?
I'm writing a greasemonkey javascript that grabs some raw data, runs some regex on it, then runs some more regex on it to refine the results:
// I tried this on :: http://stackoverflow.com/
var tagsraw = (document.getElementById("subheader").innerHTML);
alert(tagsraw);
Getting the raw data (above code) works
var trimone = tagsraw.match(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g);
alert(trimone);
running regex once works (above code); but running (code below) doesn't??
var trimtwo = trimone.match(/\s\w+\s\w+\s\w+\s\w+/g);
alert(trimtwo);
Can some advise me as to what is wrong with my code/approach?
The reason the first match works, is because innerHTML returns a string.
However the match returns an array, thus treat it as one:
for (var i=0; i<trimone.length; i++)
{
var trimtwo = trimone[i].match(/\s\w+\s\w+\s\w+\s\w+/g);
alert(trimtwo);
}
Edit:
Try this code instead though, I think this is a bit closer to what you want to achieve:
var trimone = tagsraw.match(/title\s*=\s*".*"/g);
alert(trimone);
for (var i=0; i<trimone.length; i++)
{
alert(trimone[i]);
}
You could do something like this:
var str = "<title> foo bar baz quux blah</title>",
re = [
/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g,
/\s\w+\s\w+\s\w+\s\w+/g
],
tmp = [str];
for (var i=0, n=re.length; i<n; ++i) {
tmp = tmp.map(function(val) {
return val.match(re[i])[0];
});
}
alert(tmp);
.match should be returning an array, not a string.
Your case is better suited to using .exec. You could even chain the two if you don't care about the intermediate result:
/\s\w+\s\w+\s\w+\s\w+/g.exec(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g.exec(tagsraw));
The problem is that match() returns an array and there is no built-in function to perform a regular expression on an array.
So instead you should be able to do this with the exec function from the Regexp object. It will return the matched string. You can grab the matched string from the first regexp and use it for the second.
So it'd be something like this:
var patt1 = new Regexp(/title\W\W\w+\s\w+\s\w+\s\w+\s\w+/g);
var trimone = patt1.exec(tagsraw);
if (trimone != null) // might be null if no match is found
{
alert(trimone);
var patt2 = new Regexp(/\s\w+\s\w+\s\w+\s\w+/g);
var trimtwo = patt2.exec(trimone);
alert(trimtwo);
}
Note that exec returns null if no match is found so be sure to handle that in your code like I do above.

Categories