faqts : Computers : Programming : Languages : JavaScript : Language Core : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 27 people (70%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How do I make every word in a string start with a capital letter?
How can I convert a string so that every word starts with a capital letter?

Mar 19th, 2000 16:10
Martin Honnen,


Using an appropriate regular expression and the replace method of 
strings with a custom replace function that is easy.
The regular expression to match every word boundary followed by an 
alphanumerical letter is
  var re = /\b\w/g;
The (anonymous) function to pass to replace simply takes the whole 
match and calls toUpperCase on it:
  function (s1) {
    return s1.toUpperCase();
  }
Then define a string e.g.
  var string = 
    'kibology for all. all for kibology.\n' +
    'scriptology at javascript.faqts.com.';
and call replace on it with the regular expression and the function as 
the arguments:
  string = 
    string.replace(re, function (s1) { return s1.toUpperCase(); });
  alert(string);

Simply and elegant isn't it? Unfortunately that function as a second 
parameter to the replace method was only introduced in JavaScript 1.3 
and is not supported before JScript 5.5.

So for JavaScript 1.2 and JScript we need to loop through the string:

function capitalLetter (string) {
  var match;
  var r = '';
  if (document.all) {
    var re = /\b\w/g;
    while ((match = re.exec(string))) {
      re = /(.|\n)\b\w/g;
      r += string.substring(0, match.index) + match[0].toUpperCase();
      string = string.substring(match.index + match[0].length);
    }
    r += string;
  }
  else {
    var re = /\b\w/g;
    var ind = 0;
    while ((match = re.exec(string))) {
      r += string.substring(ind, match.index) + match[0].toUpperCase();
      ind = re.lastIndex;
    }
    r += string.substring(ind)
  }
  return r;
}
var string = 
    'kibology for all. all for kibology.\n' +
    'scriptology at javascript.faqts.com.';
string = capitalLetter(string);
alert(string)

As JScript (at least including JScript 5) has a bug with regular 
expressions the function capitalLetter contains different code for IE 
and other browsers.