2013-04-04 47 views
3

我正在爲網站的後端輸入文本。我想要一些東西自動更正。例如,我將textarea中的新行轉換爲<br>。我也想讓用戶在新行上標籤。將多個空格轉換爲 使用Javascript開始行

這需要更改空間到&nbsp;。我只想轉換位於新行開頭的空格。例如,假設用戶鍵入此爲一個textarea:

This is my text! It's pretty great. 
This is a second line. 
    This is a third line, that is indented by four spaces. 
This is a fourth line. 

使用正則表達式,我已經得到了各行的第一個空間轉換:

.replace(/^[ ]/mg,'&nbsp;'); 

我已經得到多個空格轉換爲一個空間:

.replace(/[ ]{2,}/mg,'&nbsp;'); 

我不知道如何轉換所有四個這些縮進空間雖然。我一直在互聯網上搜索大約3個小時,我發現了類似的答案,但沒有什麼可以在這裏工作的。有什麼想法嗎?

回答

4
function escapeSpaces(str) { 
    var regex = /^ +/mg; 

    return str.replace(regex, function (match) { 
     var result = ""; 
     for (var i = 0, len = match.length; i < len; i++) { 
      result += "&nbsp;"; 
     } 
     return result; 
    }); 
} 

這可能不是最好的解決方案,但它的工作原理。

或者:

function escapeSpaces (str) { 
    return str.replace(/^ +/mg, function (match) { 
     return match.replace(/ /g, "&nbsp;"); 
    }); 
} 
+0

這些的兩個工作,直到我取代換行符 '\ n' 與
。這打破了他們。 – 2013-04-10 13:31:10

+1

捕獲括號是不必要的,並且效率稍低。使用'match'而不是'spaces'去除它們和'spaces'參數。另外,如果沒有*空格,則不需要替換,所以使用'+'而不是'*'。 – PointedEars 2013-04-10 13:48:23

+0

@AndyM「醫生,如果我移動它,我的手臂會疼。」不要這樣做。 *稍後*。 – PointedEars 2013-04-10 13:57:26