最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Removing all space from an array javascript - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked Dec 10, 2017 at 3:44 burrowfestorburrowfestor 371 silver badge4 bronze badges 3
  • 1 You need to replace individual element: wordlist[i] = wordlist[i].replace(/\s+/, "");. Try using something like map, it's a much cleaner approach. Note that your replacement function will replace any whitespace. If you want to just trim, use the trim function: wordlist[i] = wordlist[i].trim() – nem035 Commented Dec 10, 2017 at 3:46
  • [book, row boat,rain coat] - Doesn't look like a string array. Is this one string or are you getting back [" book", " row", " boat", " coat"] – nipuna-g Commented Dec 10, 2017 at 3:47
  • Do you want ALL whitespace or just the preceding and trailing whitespace? So if your array is something like this: ["cat food","dogs ","fish tank"] do you want the spaces within cat food and fish tank gone too? Or will there never be any spaces within the strings? – Intervalia Commented Dec 10, 2017 at 3:55
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

发布评论

评论列表(0)

  1. 暂无评论