-3

I have a varying number of elements in an object called foo

Not knowing the number of objects in advance, how can I convert all multiple whitespaces into one whitespace?

so that

var foo = [[day_1: "Hello World   "], [day_2:"  Hello World"], [day_3: "Hello World   "], [day_4: "Hello World"], [day_5:"     Hello World   "], [day_6: "Hello World"], [day_7: "Hello  World"]] 

would become:

var output = [[day_1: "Hello World "], [day_2: " Hello World"], [day_3: "Hello World "], [day_4: "Hello World"], [day_5: " Hello World "], [day_6: "Hello World"], [day_7: "Hello World"]]

I have tried this so far but it is does not produce the expected output as it should be in a for each loop format:

foo.replace(/ +(?= )/g,'')
iskandarblue
  • 7,208
  • 15
  • 60
  • 130

2 Answers2

0

So if I'm understanding correctly, you want to iterate through the array and replace all runs of whitespace with a single space. This can be done like so:

var output = [];
for (var i = 0; i < foo.length; i++) {
    output.push(foo[i].replace(/ +/g, ' '));
}

Unless I'm missing something, there should be no need for the positive lookahead you've applied in your regex.

You could alternately do this in a functional style, like so:

var output = foo.map(function(part) { return part.replace(/ +/g, ' ') });
furkle
  • 5,019
  • 1
  • 15
  • 24
0

You want to iterate through the array and replace all occurences of whitespace with a single space. This can be done like this:

var output = [];
for (var i = 0; i < foo.length; i++) {
    var temp={};
    Object.getOwnPropertyNames(foo[i]).forEach(function(val, idx, array) {        
       temp[val]=foo[i][val].replace(/\s+/g, ' ');
    });
    output.push(temp);
}

It seems that you tried applying the method to the whole array, and forgot to apply it to each string in the array.

Also FYI:

The \s in the regex replaces all whitespace, not just spaces.

This iterates through each one of each objects' properties and replaces the values of each one.

C L K Kissane
  • 34
  • 1
  • 5