Transform ALL CAPS to Proper Case using CSS and jQuery

前端 未结 2 1611
灰色年华
灰色年华 2020-12-18 11:24

I\'m trying to do something similar to this thread https://stackoverflow.com/a/3471258/2117845 and I think I want something like Harmen posted with the jquery code and said

相关标签:
2条回答
  • 2020-12-18 11:55

    I modified the code from Greg Dean's answer in a related question.

    I would call this algorithm an educated guess at best since it's not actually evaluating English capitalization rules. You'll probably need to add more words to the noCaps list for better accuracy.

    Example

    JS

    var ele = $('p'); 
    ele.text(toProperCase(ele.text())); 
    
    function toProperCase(str)
    {
        var noCaps = ['of','a','the','and','an','am','or','nor','but','is','if','then', 
    'else','when','at','from','by','on','off','for','in','out','to','into','with'];
        return str.replace(/\w\S*/g, function(txt, offset){
            if(offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1){
                return txt.toLowerCase();    
            }
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    }
    

    HTML

    <p>THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</p>
    
    0 讨论(0)
  • 2020-12-18 12:00

    I have just modified the code by Harmen to fit your needs. put it inside your JS file.

    jQuery.fn.ucwords = function() {
       return this.each(function(){
          var val = $(this).text().toLowerCase(), newVal = '';
          val = val.split(' ');
    
          for(var c=0; c < val.length; c++) {
             if (c>0 && val[c]=="is" || c>0 && val[c]=="to" || c>0 && val[c]=="the"){
                 newVal+=val[c]+' ';
             } else newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
    
          }
          $(this).text(newVal);
      });
    }
    
    $(document).ready(function(e) {
        $('p.link').ucwords();
    });
    

    HTML for the example

    <p class="link">THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</p>
    

    and JSFiddle for you http://jsfiddle.net/fqEvX/

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