-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,'') 
0

2 Answers 2

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, ' ') }); 
Sign up to request clarification or add additional context in comments.

2 Comments

I get foo.map is not a function - I edited the question = foo is actually an Object containing a an array
Apologies, I have edited the original question
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.

4 Comments

That's not really what \W does -- I think you want \s.
Thanks I'll correct that.
I have edited the original question - foo is actually an object
Ok updated answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.