Is there a built in way with jQuery to \"title case\" a string? So given something like bob smith, it turns into \"Bob Smith\"?
You can also use method like this -
toTitleCase: function (str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
If you want to combat the terrible people in the world who TYPE IN ALL CAPS, and also title case it at the same time, you can use this variation of the top answer here:
function toTitleCase(str) {
var lcStr = str.toLowerCase();
return lcStr.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
alert(toTitleCase("FOO BAR baz")); // alerts "Foo Bar Baz"
is way more simple...
You have to use a callback in replace.
toCamelCase = function(str){
return str.replace(/-\w/g,function(match){return match[1].toUpperCase()})
}
// this works for css properties with "-"
// -webkit-user-select => WebkitUserSelect
You can change the RegExp to /[-\s]\w/g or /(^|[-\s])\w/g or other...
You can also implement a pure javascript extension method like this:
String.prototype.capitalize = function () {
return this.toLowerCase().replace(/\b[a-z]/g, function (letter) {
return letter.toUpperCase();
});
};
And call it like this:
"HELLO world".capitalize()
In jQuery 1.4+ (at least) you can use
var camelized = jQuery.camelCase("some-string");
// Returns "someString"
I could not find it when I last checked the documentation, but it's there and used internally.
Use inbuilt camelcase method in jquery:
$.camelCase($("#text").html());