First Word Retrieval from a sentence

Discussion in 'JavaScript' started by pb60704, Nov 16, 2009.

  1. #1
    Hi,
    I want to display only the first word in a sentence.Please let me know how can I do this by using Javascript.
    Thanks in advance.
     
    pb60704, Nov 16, 2009 IP
  2. shubhamjain

    shubhamjain Active Member

    Messages:
    215
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    63
    #2
    var s="This is a sentence";
    var first_word=s.split(" ")[0];
     
    shubhamjain, Nov 16, 2009 IP
  3. mps705

    mps705 Peon

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Maybe you should trim the sentence first so you won't hit a problem if the string starts with spaces :

    var s="This is a sentence";
    s= s.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var first_word=s.split(" ")[0];
     
    mps705, Nov 17, 2009 IP