Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all space from an array javascript

I have an array that I need to remove spaces from, for example it returns like

[book, row boat,rain coat]

However, I would like to remove all the white spaces.

All the guides I saw online said to use .replace, but it seems like that only works for strings. Here is my code so far.

function trimArray(wordlist)
{
    for(var i=0;i<wordlist.length;i++)
    {
        wordlist[i] = wordlist.replace(/\s+/, "");
    }

}

I have also tired replace(/\s/g, '');

Any help is greatly appreciated!

like image 809
burrowfestor Avatar asked Jul 21 '26 00:07

burrowfestor


2 Answers

First and foremost you need to enclose the words in your array quotes, which will make them into strings. Otherwise in your loop you'll get the error that they're undefined variables. Alternatively this could be achieved in a more terse manner using map() as seen below:

const arr = ['book', 'row boat', 'rain coat'].map(str => str.replace(/\s/g, ''));

console.log(arr);
like image 117
Carl Edwards Avatar answered Jul 22 '26 12:07

Carl Edwards


This will remove all of the spaces, even those within the text:

    const result = ['  book','  row boat  ','rain coat  '].map(str => str.replace(/\s/g, ''));
    console.log(result);

and this will only remove preceding and trailing spaces:

    const result = ['  book',' row boat ','rain coat   '].map(str => str.trim());
    console.log(result);
like image 29
Intervalia Avatar answered Jul 22 '26 13:07

Intervalia