[英]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". 我想将“FLAT RATE”转换为“FLATRATE”和“FREE SHIPPING”转换为“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: 您可以使用array.map
函数在数组中循环并使用正则表达式删除所有空格:
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 .map确实是要走的路,但既然已经给出了,而且因为我喜欢链接,我给了另一个(快速而肮脏)的解决方案
You really don't need jQuery for that. 你真的不需要jQuery。
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. 您可以使用replace函数来实现此目的。
var shipping = ["FLAT RATE", "FREE SHIPPING"];
var without_whitespace = shipping.map(function(str) {
replaced = str.replace(' ', ''); return replaced;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.