Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Friday, June 1, 2012
Capitalize the first letter of string in JavaScript
I want to capitalize the first character of a string, but not change the case of any of the other letters. For example:
Here is a function called ucfirst() (short for "upper case first letter"):
function ucfirst(str) { var firstLetter = str.substr(0, 1); return firstLetter.toUpperCase() + str.substr(1); }
You can capitalise a string by calling ucfirst("some string") -- for example,
ucfirst("this is a test") --> "This is a test"
It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).
You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in Javascript, when you take a substring of an empty string, you just get an empty string back.
If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:
String.prototype.capitalize = function () { return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); }) }
Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.
Okay so I am a Javascript noob. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):
String name = request.getParameter("name"); name = name.toUpperCase().charAt(0) + name.substring(1); out.println(name);
Here I get the Variable from a Form,... it also works manually...
String name = "i am a Smartypants..."; name = name.toUpperCase().charAt(0) + name.substring(1); out.println(name);
If I may alter the code a little. I found that if I run an all caps string through this function, nothing happens. So... here is my tid bit. Force the string to lower case first.
Another solution:
ReplyDeletefunction capitaliseFirstLetter(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
A more object-oriented approach:
ReplyDeleteString.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
And then:
"hello world".capitalize(); => "Hello world"
Here is a shortened version of the popular answer that gets the first letter by treating the string as an array:
ReplyDeletefunction capitaliseFirstLetter(string)
{
return string[0].toUpperCase() + string.slice(1);
}
Seems to be easier in CSS...
ReplyDelete<style type="text/css">
p.capitalize {text-transform:capitalize;}
</style>
<p class="capitalize">This is some text.</p>
from: http://www.w3schools.com/cssref/pr_text_text-transform.asp
If you are wanting to reformat all-caps text, you might want to modify the other examples as such:
ReplyDeletefunction capitalize (text) {
return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}
This will ensure that the following text is changed:
TEST => Test
This Is A TeST => This is a test
String.prototype.capitalize = function(){
ReplyDeletereturn this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase();
} );
};
Usage:
capitalizedString = someString.capitalize();
this is a text string => This Is A Text String
Capitalize the first letter of all words in a string:
ReplyDeletefunction ucFirstAllWords( str )
{
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ )
{
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
Here is a function called ucfirst() (short for "upper case first letter"):
ReplyDeletefunction ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
You can capitalise a string by calling ucfirst("some string") -- for example,
ucfirst("this is a test") --> "This is a test"
It works by splitting the string into two pieces. On the first line it pulls out firstLetter and then on the second line it capitalises firstLetter by calling firstLetter.toUpperCase() and joins it with the rest of the string, which is found by calling str.substr(1).
You might think this would fail for an empty string, and indeed in a language like C you would have to cater for this. However in Javascript, when you take a substring of an empty string, you just get an empty string back.
The ucfirst function works if you do it like this
ReplyDeletefunction ucfirst(str) {
var firstLetter = str.slice(0,1);
return firstLetter.toUpperCase() + str.substring(1);
}
Thanks J-P for the aclaration.
If you go with one of the regex answers, remember they will only work with ASCII characters. All your unicode letters will not be uppercased. The XRegExp library and its unicode plugins solve this problem if you want to stick with regexps. So something like this would work:
ReplyDeleteString.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
Considering that it still doesn't cover all possibilities (combined characters, see http://www.regular-expressions.info/unicode.html) it seems easier to just use the .charAt(0).toUpperCase() approach.
Okay so I am a Javascript noob. I wasn't able to get the above to work for me. So I started putting it together myself. Here's my idea (about the same, different and working syntax):
ReplyDeleteString name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
Here I get the Variable from a Form,... it also works manually...
String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
Output: "I am a Smartypants...";
Good luck everyone.
If I may alter the code a little. I found that if I run an all caps string through this function, nothing happens. So... here is my tid bit. Force the string to lower case first.
ReplyDeleteString.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
}
CoffeeScript
ReplyDeleteucfirst = (str) -> str.substr(0, 1).toUpperCase() + str.substr(1)