Is there a built in way with jQuery to \"title case\" a string? So given something like bob smith, it turns into \"Bob Smith\"?
function camelCase(str){
str = $.camelCase(str.replace(/[_ ]/g, '-')).replace(/-/g, '');
return str;//.substring(0,1).toUpperCase()+str.substring(1);
},
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('.clsToTitleCase').keyup(function () {
this.value = this.value.replace(/(?:^|\s)\w/g, function (match) {
return match.toUpperCase();
})
});
})
</script>
<body>
<input class='clsToTitleCase' type='text'>
</body>
</html>
You don't need jQuery for this; it can be accomplished using the native .replace() method:
function toTitleCase(str) {
return str.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
alert(toTitleCase("foo bar baz")); // alerts "Foo Bar Baz"
You can use css, like:
.className
{
text-transform:capitalize;
}
This capitalizes the first letter. You can read more here
There isn't anything built-in to jQuery that does it, but you can checkout this site that has a basic code example:
http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
String.prototype.toCamel = function(){
return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};
It would seem that from there you could call the code like so:
var str = "my string to camel case";
str = str.toCamel();
if ( typeof console !== 'undefined' ) console.log(str);
I know this question is a bit old but,
Here's my version of camelCase function:
var camelCase = (function () {
var DEFAULT_REGEX = /[-_]+(.)?/g;
function toUpper(match, group1) {
return group1 ? group1.toUpperCase() : '';
}
return function (str, delimiters) {
return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
};
})();
It handles all of the following edge cases:
Here's a link to live tests: http://jsfiddle.net/avKzf/2/
Here are results from tests:
Notice that strings that start with delimiters will result in a uppercase letter at the beginning. If that is not what you would expect, you can always use lcfirst. Here's my lcfirst if you need it:
function lcfirst(str) {
return str && str.charAt(0).toLowerCase() + str.substring(1);
}