Select 两个词之间的词

Select word between two words

我如何创建一个函数来选择单词 X 和 Y 之间的所有内容并将其推送到数组。

By Greili - 4 Hours and 40 Minutes ago.
#NsShinyGiveaway
0 comments

By ToneBob - 4 Hours and 49 Minutes ago.
#NsShinyGiveaway
0 comments

By hela222 - 5 Hours and 14 Minutes ago.
#NsShinyGiveaway
sure why not? XD
0 comments

By NovaSplitz - 5 Hours and 45 Minutes ago.
#NsShinyGiveaway Enjoy life off PokeHeroes buddy.
0 comments

鉴于上面的文字,我想将 "By" 之后和 SPACE 之前的每个单词推送到一个数组中。结果必须是这样的:

name[0] = "Greili"
name[1] = "ToneBob"
name[2] = "hela222"

尝试使用正则表达式:

var regex = /By ([^\s]+)\s/g;
var s = 'string to search goes here';
var names = [];
var result;
do {
    result = regex.exec(s);
    if (result) {
        names.push(result[1]);
    }
} while (result);

JSFiddle Example

我看到你想要的词总是第二个词,所以这是解决问题的更简单的方法。您可以在每个 space 上拆分字符串,然后得到一个单词数组,其中索引 1 处的单词是您想要的名称。然后将每个名称添加到一个新数组中。

var words = "By Greili ...".split(" ");
var name = words[1]; // "Greili"
var namesArray = [];
namesArray.push(name);

您需要在循环中为每个评论字符串执行此操作。

这是一个快速 split and reduce:

var arr = str.split("By ").reduce(function(acc, curr) {
  curr && acc.push(curr.split(" ")[0]); return acc;
}, []);

结果:

["Greili", "ToneBob", "hela222", "NovaSplitz"]

演示:JSFiddle