使用正则表达式连接数组元素

时间:2012-06-25 17:21:23

标签: jquery regex join

是否可以使用正则表达式连接数组元素?如果是这样,我如何实现这些要求?

  • 每个元素都应该用间距字符连接,除非它是一个空元素。
  • 空数组元素应与新行字符(\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.

3 个答案:

答案 0 :(得分: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​;​

答案 1 :(得分: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

答案 2 :(得分:0)

您应该首先使用匹配/替换循环来根据您的规则修改元素,然后您应.join生成的数组。