将字符串拆分为每个索引n个字的数组

时间:2014-05-11 19:05:11

标签: javascript arrays regex string

我有一个字符串,我想分成一个数组,每个索引有3个单词。 我还想要它做的是,如果遇到该字符串中的新行字符,它将“跳过”3个字的限制并将其放入新索引并开始在该新索引中添加单词,直到它再次达到3 。示例

var text = "this is some text that I'm typing here \n yes I really am"

var array = text.split(magic)

array == ["this is some", "text that I'm", "typing here", "yes I really", "am"]

我已经尝试过查看正则表达式,但到目前为止,我还无法理解正则表达式中使用的语法。

我已经编写了一种复杂函数的方法,它将我的字符串拆分为3行,首先使用.split(" ");将其拆分为单独的单词数组,然后使用循环将其添加到另一个数组中。但有了这个,我不能考虑新的线字符。

5 个答案:

答案 0 :(得分:4)

您可以尝试使用此模式:

var result = text.match(/\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g);

因为量词{0,2}默认是贪婪的,所以只有在找到换行符时才会取小于2 <(N-1)的值(因为换行符不是允许这里:[^\w\n]+或者如果你是字符串的结尾。

答案 1 :(得分:2)

如果您对正则表达式解决方案感兴趣,可以这样:

   text.match(/(\S+ \S+ \S+)|(\S+ \S+)(?= *\n|$)|\S+/g)
   // result ["this is some", "text that I'm", "typing here", "yes I really", "am"]

说明:匹配三个空格分隔的单词,或两个单词后跟空格+换行符,或只有一个单词(一个&#34;单词&#34;只是一个非空格序列)。

对于任意数量的单词,请尝试:

text.match(/((\S+ ){N-1}\S+)|(\S+( \S+)*)(?= *\n|$)|\S+/g)

(用数字替换N-1)。

答案 2 :(得分:1)

尝试这样的事情:

words = "this is some text that I'm typing here \n yes I really am".split(" ");
result = [];
temp = "";

for (i = 0; i < words.length; i++) {
  if ((i + 1) % 3 == 0) {
    result.push(temp + words[i] + " ");
    temp = "";
  } else if (i == words.length - 1) {
    result.push(temp + words[i]);
  } else {
    temp += words[i] + " ";
  }
}

console.log(result);

基本上这是通过单词分割字符串,然后遍历每个单词。它获得的每三个单词,它会将temp中存储的内容添加到数组中,否则会将该单词添加到temp

答案 3 :(得分:0)

只有当你知道没有'左'字时,所以单词的数量总是3的倍数:

"this is some text that I'm typing here \n yes I really am".match(/\S+\s+\S+\s+\S+/g)
=> ["this is some", "text that I'm", "typing here \n yes", "I really am"]

但是如果你添加一个词:

"this is some text that I'm typing here \n yes I really am FOO".match(/\S+\s+\S+\s+\S+/g)

结果将完全相同,因此缺少“FOO”。

答案 4 :(得分:0)

这里还有一个方法: 使用这种模式((?:(?:\S+\s){3})|(?:.+)(?=\n|$))
Demo