jQuery Title Case

后端 未结 13 2115
小鲜肉
小鲜肉 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:41

    I have modified rBizzle's code slightly. I don't want to mess with the McClouds and McIntosh's of the world (I'm listening to Celtic music right now!), so I added a condition to only modify if ALL CAPS or ALL lowercase:

    function isUpperCase(str) {
        return str === str.toUpperCase();
    }
    
    function isLowerCase(str) {
        return str === str.toLowerCase();
    }
    
    function toProperCase(str) {
    	//only mess with it if it is all lower or upper case letters
    	if (isUpperCase(str) || isLowerCase(str)){
    	 	var lcStr = str.toLowerCase();
        	return lcStr.replace(/(?:^|\s)\w/g, function(match) {
           	 	return match.toUpperCase();
        	});	
    	} else {
    		return str;
    	}
    }

    I am mostly trying to contend with the users WHO INSIST ON YELLING THEIR DATA ENTRY! It's one thing for internal data, but when customers are going to see it, I have to draw the line.

    0 讨论(0)
提交回复
热议问题