简体   繁体   中英

How can I remove white space between words in an array using Javascript?

In the below array, how can I remove whitespace between words within each string? I want to convert "FLAT RATE" to "FLATRATE" and "FREE SHIPPING" to "FREESHIPPING".

在此输入图像描述

I had to work out with array. I saw the solutions for simple string's case.

a string can be split and joined this way:

s.split(" ").join("");

That removes spaces.

You can use array.map function to loop in array and use regex to remove all space:

 var array = ['FLAT RATE', 'FREE SHIPPING']; var nospace_array = array.map(function(item){ return item.replace(/\\s+/g,''); }) console.log(nospace_array) 

  ['FLAT RATE', 'FREE SHIPPING'].toString().replace(/ /g,"").split(",") 

I admit : not the best answer, since it relies on the array strings not to contain a comma.

.map is indeed the way to go, but since that was already given, and since I like chaining, I gave another (quick and dirty) solution

You really don't need jQuery for that.

var ListOfWords = ["Some Words Here", "More Words Here"];
for(var i=0; i < ListOfWords.length; i++){
    ListOfWords[i] = ListOfWords[i].replace(/\s+/gmi, "");
}
console.log(ListOfWords);

You can use the replace function to achieve this.

var shipping = ["FLAT RATE", "FREE SHIPPING"];

var without_whitespace = shipping.map(function(str) {
   replaced = str.replace(' ', ''); return replaced;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM