FWIW, this is kind of a nonsensical way to do this, no matter how you look at it.
More sensiible, in my opinion:
Code:
var text="My name is Tim and not Thomas"
var words = text.split(/\b/g); // the \b there says "break on word boundaries"
var found = [ ];
for ( var w = 0; w < words.length; ++w )
{
var word = words[w];
if ( word.charAt(0) == "T" )
{
found.push( word );
}
}
At the end of this code,
found will have two elements: "Tim" and "Thomas".
If you preferred to collect the *letters* of each:
Code:
if ( word.charAt(0) == "T" )
{
for ( var c = 0; c < word.length; ++c )
{
found.push( word.charAt(c) );
}
}
If you really do want only 3 letters per found word (why??), then:
Code:
if ( word.charAt(0) == "T" )
{
for ( var c = 0; c < word.length && c < 3; ++c )
{
found.push( word.charAt(c) );
}
}
It makes much more sense to break the string into "words". You now only have to check the first letter of each word, not every character in the string.