Link to home
Start Free TrialLog in
Avatar of fayezsaad
fayezsaad

asked on

Get the first word from sentence field

Hi ,

I am new in javascript. I need a code that get only the first word from the sentence field and make the word in lowercase onblur .
Avatar of Sys_Prog
Sys_Prog
Flag of India image

Hi fayezsaad,

Use indexOf() to search space and use substring() to get the first word
Use toLowerCase() to change to lowercase
append the remaining string to this changed value and assign it back to the control

http://www.w3schools.com/jsref/jsref_obj_string.asp

Cheers!
Avatar of smaccari
smaccari

Here is an example though:

<input type=text onblur="changeCase(this)"/>

<script>
function changeCase(obj)
{
   var str=obj.value;
   var firstWord=str;
   if (str.indexOf(" ")!=-1) firstWord=str.substring(0,str.indexOf(" "));
   firstWord=firstWord.toLowerCase();
   var newValue="";
   if (str.indexOf(" ")!=-1) newValue=firstWord+str.substr(str.indexOf(" "));
   else newValue=firstWord;
   obj.value=newValue;
}
</script>
Avatar of TimYates
Or you can do it with Regexp if the mood takes you ;-)

<html>
  <body>
    <script type="text/javascript">
  function doit( aTextField )
  {
    var aTxt = aTextField.value ;

    var words = aTxt.match( /(\S+).*/ ) ;
    if( words && words.length > 1 )
    {
      aTxt = aTxt.replace( /\S+/, words[ 1 ].toLowerCase() ) ;
      aTextField.value = aTxt ;
    }
  }
    </script>
    <textarea onblur="doit( this )"></textarea>
  </body>
</html>
ASKER CERTIFIED SOLUTION
Avatar of REA_ANDREW
REA_ANDREW
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fayezsaad

ASKER

Thanks All for your help.