• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1991
  • Last Modified:

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 .
0
fayezsaad
Asked:
fayezsaad
1 Solution
 
Sys_ProgCommented:
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!
0
 
smaccariCommented:
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>
0
 
TimYatesCommented:
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>
0
 
REA_ANDREWCommented:
here is a function which you can specify which word you would like to get

<script language="javascript">
function getWord(str,pos)
{
      var SplitString = str.split(" ");
      alert(SplitString[parseInt(pos)-1]);
}
</script>

an example of this in action is here

<html>

<head>
<script language="javascript">
function getWord(str,pos)
{
      var SplitString = str.split(" ");
      alert(SplitString[parseInt(pos)-1]);
}
</script>

<title>New Page 1</title>
</head>

<body>

<script language="javascript">
      getWord("this is a test STring",3)
</script>

</body>

</html>
0
 
fayezsaadAuthor Commented:
Thanks All for your help.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now