View Single Post
Old 12-19-2012, 03:42 AM   PM User | #12
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote