I don't think the answer of this problem is very difficult but I just can't get it to work!
I have this div where answers are stored like ("A""B""C") etc. I am reading this div with jQuery so I can calculate the score, so far so good.
Because I need to get each answer individually I am splitting the answers like this:
var totalAnswer = $(correctAnswer.split(/A/g).length - 1);
Above I calculate the "A" answers and count them.
The problem is that it returns it like this:
[3] instead of just 3 without the []. Is there a way I can remove the brackets?
No idea why you're wrapping with jquery object. I'd say you just need to replace
var totalAnswer = $(correctAnswer.split(/A/g).length - 1);
by
var totalAnswer = correctAnswer.split(/A/g).length - 1;
Related
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed last year.
I have multiple in my code, each with class="output" and unique IDs.
<p>Workers: <span class="output" id="workersOutput">0</span><span class="output" id="workersProdOutput"></span></p>
I want to use querySelectorAll to get them addressable in js via variables/const so that I can change their values with textContent.
Individually, I would do the following to find each div, and then the second line to update it on screen.
const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;
This is really messy though when I'll have many of these to do (12 at the moment, more to come).
Using querySelectorAll, I can make some hybrid version, using their individual index numbers from the node list. It's not exactly readable or easy to use, as the data attached to each is only visible if I output it somewhere. Not to mentioned if I add more divs, those numbers will change and not be assigned to the same IDs anymore.
const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;
Couldn't I use maybe forEach to create a variable for each using the ID attached to that index number? Or something along the lines of the below example (I know that's not how that works, but I want to get the idea across):
const outputs = document.querySelectorAll('.output');
outputs.forEach((output) => {
const outputs[2] = document.getElementById(output.id);
});
I could also be way off on how to accomplish this the "right way", I'm newish to coding.
Use an object whose property names are the IDs.
const outputs = {};
document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);
I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});
This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow
I am stumped and could really use some help with this gallery I've been working on. I used Ivan's '4 lines of jquery gallery' tutorial to get me where I am at currently. Here's his demo which shows exactly how it all works http://workshop.rs/demo/gallery-in-4-lines/
I've hit the point where I would like to include a previous and back button.
As the images are named '1-large.jpg','2-large.jpg','3-large.jpg'... etc I tried using the .slice() to take the first digit then add 1 or minus 1 to it, resulting in the next/previous pic but that didn't work well at all as my javascript skills are lacking and I don't even know if it's the best way to approach it.
My question is - Is using .slice() the way to go or is there a more simpler code I can use on my buttons?
Any help would be much appreciated.
If you just want the first character of a string:
var name = "1-large.jpg";
var i = name[0];
// i is now '1'
but this won't work for i > 9, so using split would be better:
var i = name.split('-')[0];
// i is now '1'
var i = "1023-large.jpg".split('-')[0];
// i is now '1023'
and to convert string to int:
var num = parseInt("23", 10);
// num is now the number 23, not a string
I want to do form validation at user side with JavaScript (jQuery is also used). The goal is to remove nested bbCode [quote] tags deeper than level 2. Say, we have this text:
[quote=SoundMAX][quote=Laplundik][quote=SoundMAX]
blahblahblah[/quote]
blahblah
[/quote]
blah[/quote]
And get this:
[quote=SoundMAX][quote=Laplundik]
blahblah
[/quote]
blah[/quote]
My only idea is to .replace [quote] with <div>, then create DOM object and remove anything deeper than 2 with jQuery, and parse all backwards to bbCode. But that solution seems too complicated, are there more elegant one?
EDIT:
Thanks for nice solutions. Based on darioo's answer, I did this:
var text=$('#edit-privatemsgbody').val();
var tmp=[];
var level=0;
for (var i=0,l=text.length;i<l;i++){
if(text[i]=='['&&text[i+1]=='q') level++;
if(text[i-6]=='q'&&text[i-7]=='/'&&text[i-8]=='[') level--;
if(level<3) tmp.push(text[i]);
}
alert(tmp.join(''));
Which works just fine.
But idealmachine's solution was like a flash. I didn't know about replace callback function parameters before, now that is handy! I'll settle with it.
Actually, you can use regex if you look at it as a limited tool that cannot handle the nesting itself. The .replace string method can call a function to find the replacement text for each match, which allows us to track how deep we are in the markup structure (code also posted at http://jsfiddle.net/Zbgr3/3/):
var quoteLevel = 0;
alert(s.replace(/\[(\/?)quote[^\]]*\]|./gi, function(tag, slash) {
// Opening tag?
if(tag.length > 1 && !slash.length) quoteLevel += 1;
// What to strip
var strip = quoteLevel > 2;
// Closing tag?
if(tag.length > 1 && slash.length) quoteLevel -= 1;
if(strip) return '';
return tag;
}));
If you want some tolerance for errors in the markup, you could add some extra code that, for example, prevents quoteLevel from falling below zero.
Use a regular array as a stack. Every time you encounter [quote], increase your array by one using its push() method. When you encounter [/quote], decrease your array by one using its pop() method.
If you encounter [quote] and your array length is 2, remove that [quote], and remove the next [/quote] you encounter.
If you don't have the same number of open and closed quotes, then you'll have to handle that in a way you find appropriate.