Javascript/jQuery Capitalize each word with array of exceptions and words with 3 or less characters

StackOverflow https://stackoverflow.com/questions/14261882

  •  14-01-2022
  •  | 
  •  

문제

I have this code working: 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();

I would like to have a list of words of exceptions.

Also, I don't want to capitalize words with 3 or less characters.

How could I do this?

Thanks!

도움이 되었습니까?

해결책

Try something like this: 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();

currently set to ignore words shorter than 3 characters and the ones in the list

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top