jQuery大写除了单词和之外的所有内容

时间:2012-10-11 03:16:34

标签: jquery css

这是我的菜单,全部都在Capitals

<ul class="tabgic">
   <li rel="item_227" class="">
    <div>
      <div> <a class="menu_link_2" href="#">ACCIDENTAL DAMAGE AND PROPERTY</a> </div>
    </div>
   </li> 
</ul>

我想使用jQuery并对除and之外的所有内容进行大写,因此输出将为

Accidental Damage and Property

我该怎么做?

我在看this,但不确定这是否可以轻松修改?

4 个答案:

答案 0 :(得分:3)

你可以使用正则表达式。

str = str.toLowerCase().replace(/\b[a-z]/g, function(match) {
    return match.toUpperCase();
}).replace(/\bAnd\b/g, "and");

jsFiddle

单独使用CSS无法做到这一点(至少不使用目前的标记)。

jsFiddle

答案 1 :(得分:0)

var str = 'ACCIDENTAL DAMAGE AND PROPERTY';
var result = str.split(' ').map(function(v){
  v = v.toLowerCase();
  return v.replace(/^[a-z]/, function(a){
    return v === 'and' ? a : a.toUpperCase();
  });
}).join(' ');

console.log(result); //=> Accidental Damage and Property

答案 2 :(得分:0)

考虑到你提出的输出,我怀疑你确实想要Title Case(也称为Proper Case)。您可以使用链接插件(它处理标题大小写),或者您可以使用正则表达式自行滚动:

// the RegExp  \w{4,}  will capture any word composed of 4 or more characters
// where each character can match A-Z, a-z, 0-9, and _
myString = myString.toLowerCase().replace(/\w{4,}/g, function (match) {
    return match.substring(0, 1).toUpperCase() + match.substring(1);
});

答案 3 :(得分:0)

工作演示 http://jsfiddle.net/pXe44/

希望它适合原因:)

<强>码

$(document).ready(function() {
    var foo = $('.menu_link_2').text().split(' ');
    var html = '';
    $.each(foo, function() {
        if (this.toLowerCase() != "and") html += this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase() + ' ';
        else html += this.toLowerCase() + ' ';

    });

    alert(" ===> " + html);

    $('.menu_link_2').html(html);

});​
相关问题