5,426,531 members and growing! (14,779 online)
Email Password   helpLost your password?
Web Development » Client side scripting » General     Intermediate

Proper Case JavaScript Function

By Tor2k

A one-line code snippet that will turn a string into proper case form (where each letter after a space is capitalized).
Javascript, HTMLWindows, NT4, Win2K, WinXP, Win2003, IIS, Visual Studio, Dev

Posted: 16 Jul 2005
Updated: 16 Jul 2005
Views: 27,438
Bookmarked: 5 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
2 votes for this Article.
Popularity: 0.96 Rating: 3.18 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
1 vote, 50.0%
3
0 votes, 0.0%
4
1 vote, 50.0%
5

Introduction

I have long searched for a simple code snippet that would let me turn a string into its Capitalized form, known to editors as "proper case". Upon finding nothing, I tried parsing the string one character at a time and switching on the findings; I also tried splitting the string (using spaces as delimiters), altering the first character of each element and gluing the array back into a string (using spaces, Holmes). I was able to locate the characters that needed replacing in an array of either the characters themselves or their positions (indices) within the string, but then some complex code was required to put the whole thing back together.

These attempts worked just fine, but I was still aiming at a simple replace method solution. I finally got it after discovering that JScript 5.5 will take a function as the replaceText argument.

Implementation

First, let us refresh our knowledge on regular expressions. We must locate each character after a space and remember such locations. Fortunately, the regular expression object does capture 9 "submatches" or occurrences in a set of properties. The regular expression syntax for capturing any single character after a space follows:

/\s(.)/g

I rather use the space specifier \s than an actual blank in the code to improve readability and to include any form-feed, tabs, etc. in the match.

The first character of the string must be capitalized too, so we'll use the input beginning specifier and capture whatever character is exactly after it:

/^(.)

Our lookup expression then combines into:

/^(.)|\s(.)/g

Now, the use of the $n properties in the replacement text has limitations I am not going to elaborate about; in this particular case, the beauty of using a function relies on three facts:

  1. The $1 regular expression property can be used as a function argument;
  2. The $1 regular expression property can be used inside the function, and
  3. The $1 regular expression property is updated internally by the replace method after the function executes!

Because of this, the $1 property always represents the next submatch. All that is left to do is to turn the entire string into lower case and each match to upper case using our replace function:

// proper case function (JScript 5.5+)

function toProperCase(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
          function($1) { return $1.toUpperCase(); });
}

Alternatively, if you prefer, in prototype flavor:

// proper case string prptotype (JScript 5.5+)

String.prototype.toProperCase = function()
{
  return this.toLowerCase().replace(/^(.)|\s(.)/g, 
      function($1) { return $1.toUpperCase(); });
}

Bear in mind that this is no thesaurus, its primary use is for proper names, i.e. turning HECTOR J. RIVAS or hector j. rivas into Hector J. Rivas... You will need a second pass function of your device to skip articles or other words in phrases, say to turn the opening sentence in this paragraph into: Bear in Mind that this is no Thesaurus.

I sure would like to know the internals of the replace function, the regular expression object and the function as replace text, since I mostly use it in database apps, but so far, it reports better speed and efficiency than any other method I have tried.

Hope you like it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Tor2k


Born April 27, 1968 in Caracas, Venezuela, Hector J. Rivas has 24+ years of experience managing hardware and software development under many different operating systems, platforms and languages. He has developed microcontroller interfaces and PC games; authored computer based training lessons and delivered fully functional financial and administrative data-intensive applications, as well as image processing and other calculation-intensive applications. Mr. Rivas has also managed Y2K remediation, large scale platform migration and Web site projects, from R&D to actual deployment.
Occupation: Web Developer
Location: United States United States

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralWhy the function?memberChristopher Lord12:17 16 Jul '05  
GeneralRe: Why the function?memberTor2k12:57 16 Jul '05  
GeneralRe: Why the function?memberChristopher Lord19:13 16 Jul '05  
GeneralRe: Why the function?memberTor2k15:32 18 Jul '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 16 Jul 2005
Editor: Smitha Vijayan
Copyright 2005 by Tor2k
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project