4

I want remove the space in the middle of a string with $.trim() for example:

console.log($.trim("hello,           how are you?       "));

I get:

hello,           how are you?

how can I get

hello, how are you?

Thanks.

node_saini
  • 727
  • 1
  • 6
  • 22
AgainMe
  • 760
  • 4
  • 13
  • 33
  • Have you checked this ==>http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript – Karl Jan 02 '17 at 18:11

2 Answers2

15

You can use regular expression to replace all consecutive spaces \s\s+ with a single space as string ' ', this will eliminate the spaces and keep only one space, then the $.trim will take care of the starting and/or ending spaces:

var string = "hello,           how are you?       ";
console.log($.trim(string.replace(/\s\s+/g, ' ')));
KAD
  • 10,972
  • 4
  • 31
  • 73
7

One solution is to use javascript replace.

I recommend you to use regex.

var str="hello,           how are you?       ";
str=str.replace( /\s\s+/g, ' ' );
console.log(str);

Another easy way is to use .join() method.

var str="hello,           how are you?       ";
str=str.split(/\s+/).join(' ');
console.log(str);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128