3

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".

enter image description here

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

3
  • what did you done to make it? Commented Jun 11, 2017 at 18:12
  • Possible duplicate of Remove ALL white spaces from text 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 :) Commented Jun 12, 2017 at 1:25

5 Answers 5

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)

Sign up to request clarification or add additional context in comments.

Comments

4

a string can be split and joined this way:

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

That removes spaces.

2 Comments

Thanks you. Worked fine
Nice! You can accept the answer that helped you the most.
2

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

Comments

0

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

Comments

0

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

2 Comments

"FLAT RATE AMOUNT" => "FLATRATE AMOUNT".
In that case, use a regular expression. Eg Mohammad's suggestion of return item.replace(/\s+/g,'');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.