How to Capitalize Each Word of a string using JavaScript

By | June 23, 2011
In the times of “World Wide Web” everyone has heard about “JavaScript” and people like us are fully aware of its power when it comes to writing client side scripts to make your web pages interactive. We being Sage CRM Developers have been doing so many things with JavaScript and here is a tricky functionality which we achieved for one of our clients.
The client wanted to capitalize each word while displaying values of certain fields on screen irrespective of how the data was stored in database. One way was to modify the “SQL” query since that would have complicated the matter we choose JavaScript and just modified the value of the variable that is populated by SQL used to display the value on the screen, here is the snippet of the code.

Script

//’Get Value of Company Name Field
var CompName=new String(Values(‘Comp_name’));
if(CompName==”” || CompName==”undefined”) CompName=””;

if(CompName!=””)
{
//’Convert Value to Lower Case format
var CompName= CompName.toLowerCase();

//’Retrieve first world from value and convert to upper case.
var Rx= /b([a-z]+)b/ig;
CompName= CompName.replace(Rx,function(w){
return w.charAt(0).toUpperCase()+w.substring(1);
});

//’Set as Default Value
DefaultValue=CompName;
}

If you find this content useful, please drop us an email at crm@greytrix.com.