I'm trying to iterate over a whitespace delimited text record in JavaScript and retrieve the individual fields within that record. Each field is seperated by a fixed amount of spaces that is referenced within a separate JavaScript object.
var text = "apple banana orange peach ";
var whiteSpaceDictionary = {item1 : 10, item2: 8, item3: 13, item4 : 7}
Ideally i'm trying to parse this record and store them in separate variables. As in : fruit1 = 'apple; fruit2 = 'banana'; fruit 3 = 'orange'; fruit4 = 'peach';
However I'm having difficulties just printing the values seperately. Any help would be very helpful.
Here's the code I tried which didnt yield much results.
// Iterate through Dictionary
for (var key in whiteSpaceDictionary) {
// Iterate Over Text Record
for (var x = 0; x < text.length; x+=whiteSpaceDictionary[key]){
if (x == 0 ){
positionCounter = 0;
} else {
positionCounter = positionCounter + whiteSpaceDictionary[key];
}
logger.info('Field: ' + x + ' ' + text.substr(positionCounter,whiteSpaceDictionary[key]));
}
}
Note: A pre ES6 solution is preferred. Not my decision, just the system that I'm working on.