Lian Marshall
Lian Marshall

Reputation: 9

Looping through a String

I want to get every word that is shown after the word and.

var s = "you have a good day and time works for you and I'll make sure to 
get the kids together and that's why I was asking you to do the needful and 
confirm"

for (var  i= 0 ; i <= 3; i++){
    var body = s;
    var and = body.split("and ")[1].split(" ")[0];
    body = body.split("and ")[1].split(" ")[1];
    console.log(and);
}

How do I do this?!

Upvotes: 0

Views: 61

Answers (4)

Ruslan
Ruslan

Reputation: 762

Another way to do this using replace

var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"

s.replace(/and\s+([^\s]+)/ig, (match, word) => console.log(word))

Upvotes: 0

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

You can split, check for "and" word, and get next one:

var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var a = s.split(' ');
var cont = 0;
var and = false;

while (cont < a.length) {
  if (and) {
    console.log(a[cont]);	
  }
  and = (a[cont] == 'and');
  cont++;
}

Upvotes: 0

AlexiAmni
AlexiAmni

Reputation: 402

at first you need to split the whole string in "and ", after that you have to split every element of given array into spaces, and the first element of the second given array will be the first word after the "and" word.

  var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm"


        var body = s;
        var and = body.split("and ");
        for(var i =0; i<and.length;i++){
        console.log(and[i].split(" ")[0]);
        }

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074666

Simplest thing is probably to use a regular expression looking for "and" followed by whitespace followed by the "word" after it, for instance something like /\band\s*([^\s]+)/g:

var s = "you have a good day and time works for you and I'll make sure to get the kids together and that's why I was asking you to do the needful and confirm";
var rex = /\band\s*([^\s]+)/g;
var match;
while ((match = rex.exec(s)) != null) {
  console.log(match[1]);
}

You may well need to tweak that a bit (for instance, \b ["word boundary"] considers - a boundary, which you may not want; and separately, your definition of "word" may be different from [^\s]+, etc.).

Upvotes: 1

Related Questions