Slice/Split on the n'th occurence in JS - javascript

I have an array made up of strings separated by "|":
LOG: 380|2|choice|Question_8_13240_1351170102936|||incorrect|2012-10-25T15:01:13|1|<ln>380|2|choice|Question_10_13280_1351170102995|||incorrect|2012-10-25T15:01:17|1|
and need to get Question_8_13240_1351170102936 from each string so that i can see if there are any dupicate questions thus the string after the 3rd occurence of "|" and before the 4th
the code that build the array:
AssessmentManager.prototype.submit = function () {
assessData = "";
assessmentItemsLength = this.assessmentItems.length;
for (i = 0; i < this.assessmentItems.length; i++) {
if (!this.assessmentItems[i].getSubmitted()) {
assessmentFlatDataItem = this.assessmentItems[i].getFlatData();
if (assessmentFlatDataItem.length > 0) {
if (assessData.length > 0)
assessData += "<ln>";
assessData += assessmentFlatDataItem;
}
}
}
}
then GetFlatdata:
AssessmentItem.prototype.getFlatData = function () {
result = _userScormModuleId + "|";
if (this._interactionIdx)
result += this._interactionIdx;
result += "|";
if (this._interactionType)
result += this._interactionType
result += "|";
if (this._interactionId)
result += this._interactionId
result += "|";
if (this._learnerResponse)
result += this._learnerResponse
result += "|";
if (this._correctResponse)
result += this._correctResponse
result += "|";
if (this._result)
result += this._result
result += "|";
if (this._timeStamp)
result += this._timeStamp
result += "|";
if (this._weighting)
result += this._weighting
result += "|";
if (this._description)
result += this._description
return result;
}
how will i achieve this?
thanks
i have this now:
learnerResponsesArray.push({
key: j,
value: this.assessmentItems.split('<ln>')
});
then loop through learnerResponsesArray?

var cells = mystring.split("|");
// nth item...
var myitem = cells[n];
but as #mori57 said, why use this format instead of JSON?

Try this
str = "LOG: 380|2|choice|Question_8_13240_1351170102936|||incorrect|2012-10-25T15:01:13|1|<ln>380|2|choice|Question_10_13280_1351170102995|||incorrect|2012-10-25T15:01:17|1| "
console.log(str.split(":")[1].split("|")[3])

If you need the value between the 3d and 4th |, you could use:
var fourthelement = [yourstring].split(/\|/,4).pop();

Related

.innerHTML is showing up as undefined

ok so I understand this is a very basic JS logic but I am trying to replace any document.write() with .innerHTML and I tried it with the code below
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
document.write(writeString);
}
}
function newTable() {
for(let i = 1; i <= 10; i++ ) {
let para = document.getElementById("paragraph");
para.innerHTML = writeTimesTable(i)
}
}
I have a div element with the ID of paragraph already. I keep getting undefined when I look at the div#paragraph and the rest of my code outputs under my script tag but not in the div element. What am I doing wrong?
Your function writeTimesTable() needs to return a value. Your writeString string, needs to be concatenated as well, you can do that with += like seen below:
function writeTimesTable(num) {
let writeString = "";
for(let i = 1; i < 10; i++ ) {
writeString += i + " * " + num + " = ";
writeString += writeString + (i * num);
writeString += writeString + "<br />";
}
return writeString
}
Using para.innerHTML = writeTimesTable(i) probably isn't intended, as it will just display the last loop, so you might also want to use += here as well:
para.innerHTML += writeTimesTable(i)
You normally want to avoid document.write because it literally writes out to the document.
I have also taken the liberty of doing the DOM creation off-page during the loop, and just add it to the actual DOM at the end. This means you aren't constantly re-drawing the page while you loop.
This is better than changing your innerHTML = to innerHTML +=, which you would need to do if you wanted to avoid overwriting each previous iteration of the loop.
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
return writeString;
}
}
function newTable() {
const inner = document.createElement('div');
for(let i = 1; i <= 10; i++ ) {
const item = document.createElement('div');
item.innerHTML = writeTimesTable(i);
inner.appendChild(item);
}
let para = document.getElementById("paragraph");
para.appendChild(inner);
}
newTable();
<div id="paragraph"></div>
Your newTable() function with the 10 loops is useless. You're doing 10 times the same stuff over a single DOM element.
Don't use document.write...
I'd do it like:
function newTable( num ) {
var HTML = "";
for (var i=1; i <= num; i++) {
HTML += i +" * "+ num +" = "+ (i*num) +"<br>";
}
return HTML; // Return the concatenated HTML
}
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>
Or in a super uselessly cryptic ES6 way:
const newTable = n =>
Array(n).fill().map((_,i) =>
`${i+=1} * ${n} = ${i*n}<br>`
).join('');
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

javascript printing to previous line

I have a bit of code that requires printing underscores but to the line above it, how would i do this? I'm not sure how to print the underscore to the previous line, not much experience with javascript. thanks!
var landscape = function() {
var result = "";
var flat = function(size) {
for (var count = 0; count < size; count++)
result += "_";
};
var hill = function(size) {
result += " /";
for (var count = 0; count < size; count++)
result += ""+
"_";
result += " \\";
};
//BUILD SCRIPT
flat(3)
hill(4);
flat(6);
hill(1);
flat(1);
//END SCRIPT
return result;
it makes this ___ /____ \______ /_ \_`enter code here`enter code here`
and i want this
_____ ___
___/ \__/ \____/\_
You can keep track of the two lines separately and then concatenate them just before returning the result.
JS:
function landscape() {
var resultTop = '';
var resultBottom = '';
function hill(size) {
resultTop += ' ';
resultBottom += '/';
for (var i = 0; i < size; i++) {
resultTop += '_';
resultBottom += ' ';
}
resultTop += ' ';
resultBottom += '\\';
}
function flat(size) {
for (var i = 0; i < size; i++) {
resultTop += ' ';
resultBottom += '_';
}
}
flat(3);
hill(4);
flat(6);
hill(1);
flat(1);
var result = resultTop + '<br/>' + resultBottom;
return result;
}
Here's a fiddle.
One workaround is to print a unicode character that draws a line on top. Turns out there is such a character: the Upper One-eighth Block
It's "\u2594" in unicode escape or ▔ as HTML entity or you can simply copy/paste the literal character from the example below:
____/▔▔▔▔\____/▔▔\___

Uncaught TypeError: Object function has no method 'split'

No errors in the console are present, though the function does not seem to be adding the dashes like it is intended to do. Also, the code creates formatting problems on the site meaning something is wrong with this.
Code:
$('#Inventory_accountNumber').blur(function(){
var accounts = $(this).val;
var accountsNum = [];
accountNum = accounts.split(",");
for(var i=0;i<accountNum.length;i++) {
var newstr = '';
if(accountNum[i].length == 24) {
newstr += accountNum[i].substring(0,4) + '-';
newstr += accountNum[i].substring(4,7) + '-';
newstr += accountNum[i].substring(7,10) + '-';
newstr += accountNum[i].substring(10,14) + '-';
newstr += accountNum[i].substring(14,20) + '-';
newstr += accountNum[i].substring(20,24) + '-';
newstr += '0000-000';
accountNum[i] = newstr;
}
else if(accountNum[i].length == 32) {
newstr += accountNum[i].substring(0,4) + '-'
; newstr += accountNum[i].substring(4,7) + '-';
newstr += accountNum[i].substring(7,10) + '-';
newstr += accountNum[i].substring(10,14) + '-';
newstr += accountNum[i].substring(14,20) + '-';
newstr += accountNum[i].substring(20,24) + '-';
newstr += '0000-000';
accountNum[i] = newstr;
}
}
accountNum.join(',');
$(this).val = accountNum;
});
JSFiddle
This is your culprit:
var accounts = $(this).val;
That should read:
var accounts = $(this).val();
What you have there is a function reference, not the value of the function's return statement.
var accounts = $(this).val();
or
var accounts = $(this);
accountNum = accounts.val().split(",");
If you try to debug or print in your console.. an inputselector.val prints out the whole function
Also, down below
$(this).val = accountNum; is the wrong way of setting the value, use $(this).val(accountNum);

Can't get JavaScript loop to work when padded with zeroes

Trying to write some html to a div in 001, 002, 003 style format but I can't get it to work.
Here's the code:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + String.format("%03d", i) + "<br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
When I hopefully get it to work, I intend to load some images to the div like so:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + "<img src=\"" + url + "/t/" + String.format("%03d", i) + ".jpg\"></img><br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
Can't get the string formatting to work though. Not exactly sure what I'm doing wrong.
If anyone can put me straight it would be most appreciated.
Try using pad() instead of String.format().
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Add this to your page
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
And replace txt=txt... with this
txt += "<img src='" + url + "/t/" + pad(i,3) + ".jpg'></img><br/>";
Also have a look at this topic

Categories

Resources