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

jquery - How can I remove white space between words in an array using Javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Jun 12, 2017 at 1:15 sagar sapkota asked Jun 11, 2017 at 18:11 sagar sapkotasagar sapkota 1531 silver badge8 bronze badges 3
  • what did you done to make it? – tanaydin Commented Jun 11, 2017 at 18:12
  • Possible duplicate of Remove ALL white spaces from text – Crimson Commented Jun 11, 2017 at 18:13
  • I got the solution for removing white spaces in the case of simple string, But couldn't find for array. Now, I got the answer for arrays too. Thanks :) – sagar sapkota Commented Jun 12, 2017 at 1:25
Add a ment  | 

5 Answers 5

Reset to default 5

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)

a string can be split and joined this way:

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

That removes spaces.

 ['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 ma.

.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;
});
发布评论

评论列表(0)

  1. 暂无评论