Amy Neville Amy Neville - 7 months ago 11
Javascript Question

Javascript function for each double or triple words in string

Here I have some javascript to run a function for each seperate word in a string:

var input = 'this is some text';
var words = input.split(' ');
$.each(words,function(i){
//Do something
});


But how would I do something similar to run the function for each pair of words in a string? Like this:


  • this is

  • is some

  • some text



Or even triple words:


  • this is some

  • is some text


Answer

Use a common for loop instead of using a foreach loop

var words = "this is some text".split(' ');

// take the words 2 by 2
for (var i = 0; i < words.length - 1; ++i) {
    var currentWord = words[i],
        nextWord = words[i + 1];

    // do something
}

// take the words 3 by 3
for (var i = 1; i < words.length - 1; ++i) {
    var previousWord = words[i - 1],
        currentWord = words[i],
        nextWord = words[i + 1];

    // do something
}

You can also handle the general case.

var PACKET_SIZE = 2;
var words = "this is some text".split(' ');

for (var i = 0; i < words.length - PACKET_SIZE; ++i) {
    var packet = words.slice(i, i + PACKET_SIZE);

    // do something
}
Comments