Search code examples
actionscript-3text-segmentation

Remove all but the first word from a sentence


I need to find a way to take a sentence and remove all its words besides the first.

If the sentence is "Hi my name is dingo"
I need to get only the word "Hi"


Solution

  • var sentence : String = "Hi my name is dingo"
    var words : Array = sentence.split( " " );
    var firstWord : String = words[ 0 ];
    trace( firstWord ) // outputs "Hi"
    

    Obviously this only works for simple sentences without punctuation. If you need more complex word parsing you can use regexp:

    var pattern : RegExp = new RegExp( "\\b.(\\w*).\\b",'gi' );
    var words : Array = sentence.match( pattern );