NateW
NateW

Reputation: 2121

jQuery strip spaces out of array

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?

Upvotes: 1

Views: 4908

Answers (5)

Farzher
Farzher

Reputation: 14563

$(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.

Upvotes: 0

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

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

Upvotes: 5

dfsq
dfsq

Reputation: 193261

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);

Upvotes: 1

MatthewG
MatthewG

Reputation: 9293

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>

Upvotes: 0

arnolds
arnolds

Reputation: 788

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(' ', ''));
}

Upvotes: 0

Related Questions