0

我有这个代码工作:http: //jsfiddle.net/Q2tFx/

$.fn.capitalize = function () {
$.each(this, function () {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
        split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
});
return this;
};

$('.title').on('keyup', function () {
    $(this).capitalize();
}).capitalize();

我想要一份例外词列表

另外,我不想将3 个或更少字符的单词大写。

我怎么能这样做?

谢谢!

4

1 回答 1

2

尝试这样的事情:http: //jsfiddle.net/Q2tFx/10/

$.fn.capitalize = function () {
  var wordsToIgnore = ["to","and","the","it", "or", "that", "this"],
      minLength = 3;
  function getWords(str) {
    return str.match(/\S+\s*/g);
  }
  this.each(function () {
    var words = getWords(this.value);
    $.each(words,function(i,word) {
      // only continue if word is not in ignore list
      if (wordsToIgnore.indexOf($.trim(word)) == -1 && $.trim(word).length > minLength) {
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
      }
    });
    this.value = words.join("");
  });
};

$('.title').on('blur', function () {
  $(this).capitalize();
}).capitalize();

当前设置为忽略少于 3 个字符的单词和列表中的单词

于 2013-01-10T16:14:16.483 回答