I'm toying around with Javascript and I now want to extract all pairs of consecutive characters from a string. So if the string is "test" I want to output "te", "es" and "st". Now I found out how to extract single letters from a string, by treating the string as an array, and using the "in" keyword as follows:
var str = 'this is a test';
//report letters
for (var t in str) {
var c = str[t];
console.log(t + ': ' + c);
}
This seems to work. The console logs suggest that t is an index. So I figure I should be able to use t + 1 as the index for the next character in str. However, my guesses don't seem to work, when trying the following:
//report letterpairs
for (var t in str) {
var c = str[t] + str[t + 1];
console.log(t + ': ' + c);
}
This reports str[t + 1] as being "undefined".
//report letterpairs
for (var t in str) {
var c = str.substring(t, t + 1);
console.log(t + ': ' + c);
}
This returns the first character when t = 0; but a much longer substring when t = 1, and the t-th up to the last character when t >= 2.
Now I assume I can probably use a "normal" for loop using for (t = 0; t < str.length; t += 1) { }
but firstly I prefer the cleanness of the "in" keyword and want to learn how to use the "in" keyword because I'm not familiar with it from other languages. And secondly, I'd like to know why the methods above using the "in" keyword do not work. Where's the error in my line of thought?