jQuery Title Case

后端 未结 13 2114
小鲜肉
小鲜肉 2020-12-12 22:54

Is there a built in way with jQuery to \"title case\" a string? So given something like bob smith, it turns into \"Bob Smith\"?

相关标签:
13条回答
  • 2020-12-12 23:29

    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(); });
        }
    
    0 讨论(0)
  • 2020-12-12 23:32

    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"
    
    0 讨论(0)
  • 2020-12-12 23:32

    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...

    0 讨论(0)
  • 2020-12-12 23:33

    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()
    
    0 讨论(0)
  • 2020-12-12 23:39

    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.

    0 讨论(0)
  • 2020-12-12 23:41

    Use inbuilt camelcase method in jquery:

    $.camelCase($("#text").html());
    
    0 讨论(0)
提交回复
热议问题