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
  • 695
  • 1
  • 5
  • 21
AgainMe
  • 720
  • 4
  • 11
  • 32
  • 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,603
  • 4
  • 27
  • 63
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
  • 44,345
  • 11
  • 88
  • 115