2012-06-25 34 views
1

是否有可能加入一個正則表達式的數組元素?如果是這樣,我該如何達到這些要求?加入數組元素與正則表達式

  • 每個元素都應該用間距字符連接,除非它是一個空元素。
  • 空數組元素應當與一個新行字符(\n)接合。

這意味着,這樣的:

["Hello, this is a sentence.", "This is another sentence.", "", "", "Then, there are 2 new lines.","","Then just one new line."] 

應與.join被轉換成這樣的:

Hello, this is a sentence. This is another sentence. 

Then, there are 2 new lines. 
Then just one new line. 

回答

1
var string = ""; 

for(var index = 0; index < elements.length; index++) { 
    var lastElement = elements[index -1]; 
    string += elements[index] !== "" ? (lastElement && lastElement !== ""? " " + elements[index] : elements[index]) : "\n"; 
} 
console.log(string); 

DEMO

+0

幾乎可以正常工作。我仍然不知道爲什麼它會在所有句子的開頭添加空格字符。 – andufo

+0

@andufo對不起,我沒看出來。固定。 –

+0

仍然有當句子沒有他們之間的換行加入一些問題,但你給我的主要想法。我會盡力從那裏拿走它。謝謝! – andufo

1

循環通過該陣列具有取決於其中使用的是<br />\n更換空元素字符串,然後再加入它""

for (var i = 0; i < myArr.length; i++) { 
    myArr[i] = myArr[i] === "" ? "\n" : myArr[i]; 
} 
var myStr = myArr.join(""); 

編輯:這裏是一個完整的演示你的附加要求:http://jsfiddle.net/auAAH/

var myArr = ["Hello, this is a sentence.", "This is another sentence.", "", "", "Then, there are 2 new lines.", "", "Then just one new line."]; 
for (var i = 0; i < myArr.length; i++) { 
    if (myArr[i] === "") { 
     myArr[i] = "\n"; 
     if (i !== 0 && myArr[i - 1] !== "\n") { 
      myArr[i - 1] = myArr[i - 1].replace(/ $/, ""); 
     } 
    } 
    else if (i < myArr.length-1) { 
    myArr[i] = myArr[i] + " "; 
    } 
} 
var myStr = myArr.join(""); 
document.getElementsByTagName("textarea")[0].value = myStr​;​ 
+0

我使用它在一個文本。我必須加入一個空格字符,否則這些句子之間沒有空格。我也不希望換行符中有不必要的空格。 – andufo

+0

無論哪種方式,所有的改變都需要在某種類型的循環來完成。 –

0

你應該先用一根火柴/替換循環按照你的規則修改的元素,那麼你應該.join的產生陣列。