Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Convert Sentence Case

I've got some JavaScript running a convert case on some text:

$(".container").click(function(){
  text = text.toLowerCase().replace(/\b[a-z]/g, function(block){
  return block.toUpperCase();
});

Which returns given text in the container div to Sentence Case. However when an apostrophe is used in the text, such as

can't get this to work

it returns

Can'T Get This To Work

How can I make that trailing t after the apostrophe stay lowercase?

like image 560
Jordan Avatar asked Jul 17 '26 19:07

Jordan


1 Answers

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"
like image 86
Josh Crozier Avatar answered Jul 20 '26 13:07

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!