Pedro Fernandes
Pedro Fernandes

Reputation: 23

Select word between two words

How can I create a function that selects everything between the words X and Y and pushes it to an array.

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

Given the text above, I want to push each word after "By" and before SPACE onto an array. The result must be something like this:

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

Upvotes: 0

Views: 69

Answers (3)

Drakes
Drakes

Reputation: 23660

Here's a quick split and reduce:

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

Result:

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

Demo: JSFiddle

Upvotes: 2

Katie
Katie

Reputation: 66

I see the word you want is always the second word, so that's an easier way of solving the problem. You could split the string on each space, and then you have an array of words, where the word at index 1 is the name you want. Then add each name to a new array.

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

You'd need to do that for each of your comment strings, in a loop.

Upvotes: 1

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

Try using a regular expression:

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

Upvotes: 1

Related Questions