Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove space in the middle of a string with $.trim? [duplicate]

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.

like image 446
AgainMe Avatar asked Nov 29 '22 22:11

AgainMe


2 Answers

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, ' ')));
like image 94
KAD Avatar answered Dec 01 '22 14:12

KAD


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);
like image 40
Mihai Alexandru-Ionut Avatar answered Dec 01 '22 13:12

Mihai Alexandru-Ionut