1

I'm trying to strip all the spaces out of the contents of my array.

Here is my array

var array = ["option 1", "option 2", "option 3"]

I've tried using the answer found here: how do I strip white space when grabbing text with jQuery?

This is what the jQuery I'm trying to use.

$(array1).each(function(entry) {
  $(this).replace(/\s+/g, '');
  console.log(entry);
});

But it throws a TypeError: undefined is not a function (evaluating 'entry.replace(/\s+/g, '')')

What am I missing?

Community
  • 1
  • 1
NateW
  • 2,101
  • 3
  • 28
  • 37

5 Answers5

5

You can use map to make a new array.

In the map function, you use the regexp on your value.


jQuery

array = $.map(array, function(value){
  return value.replace(/ /g, '');
});

Fiddle;


Vanilla JS version

array = array.map(function(value){
  return value.replace(/ /g, '');
});

Fiddle


Old IE vanilla JS

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

Fiddle


No loop universal method (may have conflict with characters)

array = array.join('$').replace(/ /g, '').split('$');

Fiddle

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

No need to use jQuery here, just go with plain array methods like map or simple for-loop:

var array1 = ["option 1", "option 2", "option 3"].map(function(el) {
    return el.replace(/\s*/g, '')
});

document.write(array1);
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

$(this) is not what you want, you want entry, that's your string

entry = entry.replace(/\s+/g, '');

Also actually your string is the second argument. So you'd need to change your function to function(key, entry) also

That's why it doesn't work, but I recommend using some of the other solutions here. $.each isn't the best option, you want to map.

Farzher
  • 13,934
  • 21
  • 69
  • 100
0

This simple for loop, loops through the array items and removes any spaces no jQuery or regular expressions needed.

var arr = ["option 1", "option 2", "option 3"];

for (var i = 0; i < arr.length; i++) {
    alert(arr[i].replace(' ', ''));
}
arnolds
  • 778
  • 6
  • 12
0

Take a look at how 'each' works in jQuery, it is not quite what you think. This code can be fixed by noting that the first parameter to your callback is the index into the array, and so you can adjust the code like so.

var array1 = ["option 1", "option 2", "option 3"]

$(array1).each(function(entry, value) {
  array1[entry] = value.replace(/\s+/g, '');
  console.log(array1[entry]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
MatthewG
  • 8,583
  • 2
  • 25
  • 27