Web Site-Reference.com
Formatting Text Strings With JavaScript

by Amrit Hallan
Posted on May 18, 2008


In this article we'll develop an HTML form that does the following: Assuming there is some haphazard text in a text box. The various buttons on the form,

-- Remove leading and trailing spaces
-- Convert text to UPPER case
-- Convert text to lower case
-- Convert text to Title Case
-- Convert text to sentence case

Let's first design an HTML page that has the following form code:

<form name="textbox">
<textarea name="txt" cols="55"
rows="20"></textarea><br>
<input type="button" name="uc" value="All Caps"
onClick="all_caps();">&nbsp;<input type="button"
name="lc" value="All Lower Case"
onClick="all_low();">&nbsp;<input type="button"
name="tc" value="Title Case"
onClick="title_case();">&nbsp;<input type="button"
name="sc" value="Sentence Case"
onClick="sentence_case();">
</form>


There are four buttons on the form, namely, "uc" for upper case, "lc" for lower case, "tc" for title case and "sc" for sentence case.

Now for every button, we'll write the respective JavaScript functions. the rtrim() and ltrim() functions are not associated with the form buttons, they are just there to make the text look more processed. So here begins our JavaScript (my comments will appear as JavaScript comments preceded by //):

<.script language="JavaScript" type="text/javascript">
// Remove the dot before "script", I have included
this so that the
// article doesn't have a problem with your email
// reader.
function ltrim(sent_str)
// Function that removes the leading spaces.
{
var spaces=new String(" trn");
var str=new String(sent_str);
if(spaces.indexOf(str.charAt(0))!=-1)
// This checks that there really leading blanks
before
// before the string.
{
var j=0, i=str.length;
while(j<i && spaces.indexOf(str.charAt(j))!=-1)
j++;
// Keep iterating until you reach at a character
that is
// not a space.
str=str.substring(j,i);
// Copy the rest of the string.
}
return str;
}

function rtrim(sent_str)
// Function that removes the trailing spaces.
// The explanation for this function is same as the
// above function, except for it moves backward.
{
var spaces=new String(" trn");
var str=new String(sent_str);
if(spaces.indexOf(str.charAt(0))!=-1)
{
var i=str.length-1;
while(i>=0 && spaces.indexOf(str.charAt(i))!=-1)
i--;
str=str.substring(0, i+1);

}
return str;
}

function all_caps()
// This function converts the string in the text box
// to ALL CAPS.
{
var htext;
var htext=ltrim(rtrim(document.textbox.text.value));
// Here we use the functions created above.
if(htext.length<1)
{
alert("Please paste some text into the box first.");
}
else
{
document.textbox.text.value=htext.toUpperCase();
}
}

function all_low()
// This function converts the string to lower case
{
var htext;
var htext=ltrim(rtrim(document.textbox.text.value));
if(htext.length<1)
{
alert("Please paste some text into the box first.");
}
else
{
document.textbox.text.value=htext.toLowerCase();
}
}

function title_case()
// This function capitalizes the first character of
every word
// appearing in the string.
{
var htext, nhtext;
var htext=ltrim(rtrim(document.textbox.text.value));
htext=htext.toLowerCase();
// Just in case they're all caps.
j=htext.length;
nhtext="";
for(i=0;i<j;i++)
{
if(i==0)
// To capitalize the first character.
{
nhtext=nhtext+htext.substr(i,1).toUpperCase();
}
else if(htext.charAt(i)==" ")
{
// Checks for the appearance of the space character.
nhtext=nhtext+htext.substr(i,1);
// Adds that space character to the string.
nhtext=nhtext+htext.substr(++i,1).toUpperCase();
// Capitalizes and adds the next character to the
// string.
}
else if(htext.charAt(i)=="n")
{
// Checks for the appearance of the newline
character.
nhtext=nhtext+htext.substr(i,1);
// Adds the newline character to the string.
nhtext=nhtext+htext.substr(++i,1).toUpperCase();
// Capitalizes and adds the next character to the
// string.
}
else
{
nhtext=nhtext+htext.substr(i,1);
// Adds the character in a normal way.
}
}
document.textbox.text.value=nhtext;
// Done!!
}

function sentence_case()
// This function formats the text in the text box in
the
// sentence format.
{
var htext, nhtext;
var htext=ltrim(rtrim(document.textbox.text.value));
htext=htext.toLowerCase();
j=htext.length;
nhtext="";
for(i=0;i<j;i++)
{
if(i==0)
{
nhtext=nhtext+htext.substr(i,1).toUpperCase();
// The first alphabet should anyway be capitalized.
}
else if(htext.charAt(i)==".")
{
// If a period appears -- this indicates, in most of
the cases
// the end of the senstence.
nhtext=nhtext+htext.substr(i,1);
// Add the period as it is.
i++;
// Move an alphabet forward.
if(htext.charAt(i)!=" ")
// Check if no space was inserted after the
fullstop.
{
nhtext=nhtext+" ";
// Insert that space.
nhtext=nhtext+htext.substr(i,1).toUpperCase();
// Capitalize and insert the character that
appears
// in place of the missing space.
}
else
// The space was there.
{
nhtext=nhtext+htext.substr(i,1);
// Add the space.
nhtext=nhtext+htext.substr(++i,1).toUpperCase();
// Move to the next character, capitalize it,
// and add it.
}
}
else
{
nhtext=nhtext+htext.substr(i,1);
// Add the string normally.
}
}

document.textbox.text.value=nhtext;
// Done!!
}

</script>


At the first glance these function may not seem very important, but they clarify the usage of some string handling functions.


==========================================================
Amrit Hallan is a freelance web developer. You can checkout his website at http://www.bytesworth.com. For more such articles join BYTESWORTH REACHOUT at http://www.bytesworth.com/br/default.asp or if you have a web dev related question then post it at http://www.business180.com/index.php
==========================================================








Print This Article| Send To A Friend| RSS Feeds|Read More Related Articles


Print    E-mail    

Share     Text       RSS Feed



Post them now in our forums for quick, helpful advice from thousands of members!



Get all the latest webmaster tips and tricks from some of the brightest minds in the online world delivered right to your inbox with the Site-Reference Newsletter

First name:


e-mail:


Your privacy is 100% Guaranteed. Easily unsubscribe at any time



Drive traffic to your business and get recognized as an industry leader by sharing your knowledge on Site-Reference. Authors are given a wide range of exclusive benefits here at SR; so checkout what we can offer to those that…



We’re always on the lookout for new writting talent so even if haven’t written for the web yet, feel free to contact us anytime