You are here: irt.org | FAQ | JavaScript | Text | Q531 [ previous next ]
The following uses regular expressions introduced in JavaScript 1.2:
<html>
<head>
<script language="JavaScript1.2"><!--
function toUpper() {
var pattern = /(\w)(\w*)/; // a letter, and then one, none or more letters
var a = document.form1.text1.value.split(/\s+/g); // split the sentence into an array of words
for (i = 0 ; i < a.length ; i ++ ) {
var parts = a[i].match(pattern); // just a temp variable to store the fragments in.
var firstLetter = parts[1].toUpperCase();
var restOfWord = parts[2].toLowerCase();
a[i] = firstLetter + restOfWord; // re-assign it back to the array and move on
}
document.form1.text1.value = a.join(' '); // join it back together
}
//--></script>
</head>
<body>
<form name="form1">
<input type="text" name="text1">
<input type="button" onClick="toUpper()" value="To Upper Case">
</form>
</body>
</html>A couple of things to notice here - the parts array which contains the fragments found in the match (you can only use $1 and $2 within the confines of a current match) contains as the first item the entire word. This is why I get my two fragments from parts[1] and parts[2], instead of parts[0] and parts[1].
By splitting the whole sentence into chunks in the beginning, you can control the fragment you are working on. This eliminates the need to worry about spaces.
Anonymous writes:
The above method is unnecessarily CPU intensive and not correct in non-english languages. The pattern-matching can advantageously be replaced with using the substring method:
<html>
<head>
<script language="JavaScript1.2"><!--
function toUpper() {
var a = document.form1.text1.value.split(/\s+/g); // split the sentence into an array of words
for (i = 0 ; i < a.length ; i ++ ) {
var firstLetter = a[i].substring(0, 1).toUpperCase();
var restOfWord = a[i].substring(1, a.length).toLowerCase();
a[i] = firstLetter + restOfWord; // re-assign it back to the array and move on
}
document.form1.text1.value = a.join(' '); // join it back together
}
//--></script>
</head>
<body>
<form name="form1">
<input type="text" name="text1">
<input type="button" onClick="toUpper()" value="To Upper Case">
</form>
</body>
</html>The following was bubmitted by Pray:
The above 2 functions don't seem to work for me. Also, they're too much work for a programmer too actually write. This simple version is more effective, and easier to understand:
<script language="JavaScript1.2"><!--
function Capital(value) {
if (value != "") {
var firstLetter = value.substring(0, 1).toUpperCase();
var restOfWord = value.substring(1, value.length).toLowerCase();
value = firstLetter + restOfWord;
}
return value;
}
//--></script>To then use:
<form name="form1"> <input type="text" size="20" value="" maxlength="25" onBlur="this.value=Capital(this.value);"> </form>