2017-01-02 79 views
2

我想$.trim()刪除字符串中間的空間,例如:

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

我得到:

hello,   how are you? 

我怎樣才能得到

hello, how are you? 

感謝。

+0

你有沒有檢查過這個==> http://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-stri ng-in-javascript – Karl

回答

7

您可以使用正則表達式用一個空格作爲字符串' '更換所有連續的空格\s\s+,這將消除空格,只保留一個空間,那麼$.trim會照顧開始和/或結束的空間:

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

謝謝,祝大家新年快樂! – AgainMe

2

一個解決方案是使用javascript replace。我們建議您使用regex

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

另一種簡單的方法是使用.join()方法。

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