5

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.

1

2 Answers 2

16

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, ' ')));
1
  • thanks, and happy new year to all!
    – AgainMe
    Jan 2, 2017 at 18:15
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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.