0

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.

1 Answers1

0

Just match non-whitespace characters with a regular expression, and you'll have the array of values you want:

var text = "apple     banana  orange       peach  ";  
const fruits = text.match(/\S+/g);
console.log(fruits);

An array makes more sense than putting each item in a separate standalone variable, but if you wanted:

var text = "apple     banana  orange       peach  ";  
const [fruit1, fruit2, fruit3, fruit4] = text.match(/\S+/g);
console.log(fruit1);
console.log(fruit4);

If your input is actually different, and spaces can exist inside of the substrings you want to match, you'll have to iterate over the object:

var text = "apple     banana  orange       peach  ";
var whiteSpaceDictionary = {
  item1: 10,
  item2: 8,
  item3: 13,
  item4: 7
}

let last = 0;
const fruits = Object.values(whiteSpaceDictionary)
  .map(val => {
    const str = text.slice(last, last + val);
    last += val;
    return str;
  });
console.log(fruits);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • This does in fact work. One small tweak i would like to ask for. Is it possible to modify this to read fields with one or more spaces in it. As in var text = "red apple yellow banana orange yellow peach "? – Nick The Dev Jun 13 '19 at 00:37
  • You'll have to iterate over the object in that case, just keep `slice`ing from the last position sliced, to that position plus the current value being iterated over – CertainPerformance Jun 13 '19 at 00:47