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 .
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 .
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.indexO f(" "));
firstWord=firstWord.toLowe rCase();
var newValue="";
if (str.indexOf(" ")!=-1) newValue=firstWord+str.sub str(str.in dexOf(" "));
else newValue=firstWord;
obj.value=newValue;
}
</script>
<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,
firstWord=firstWord.toLowe
var newValue="";
if (str.indexOf(" ")!=-1) newValue=firstWord+str.sub
else newValue=firstWord;
obj.value=newValue;
}
</script>
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>
<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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks All for your help.
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!