The reason your expression isn't working is because a word boundary, \b
, is short for (^\w|\w$|\W\w|\w\W)
, and that doesn't include '
characters which means that the character after '
, in your case it was t
, was being selected.
You could replace \b
with (^|\s)
, which would be /(^|\s)[a-z]/g
, and that would work in your case:
$(".container").click(function() {
text = text.toLowerCase().replace(/(^|\s)[a-z]/g, function(block) {
return block.toUpperCase();
});
});
However, the best approach would be to use the regular expression \w\S*
, which will select any word characters (i.e., [a-zA-Z0-9_]
) followed by any non string character (i.e., [^\r\n\t\f ]
).
This will allow you to select each word substring. From there you can capitalize the first character and convert the remaining characters to lowercase:
$(".container").click(function() {
text = text.replace(/\w\S*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});
});
For instance, the following snippet would return:
"can't get this to work".replace(/\w\S*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});
// > "Can't Get This To Work"