いくつかのキーワードを除いて、4文字以上の単語の最初の文字を大文字にしようとしていたため、新しい質問を開くことにしました。 /11/
$.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).toLowerCase()) == -1 && $.trim(word).length > minLength) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
}
});
this.value = words.join("");
});
};
$('.title').on('keyup', function () {
$(this).capitalize();
}).capitalize();
しかし、「keyup」で関数を実行しているときに問題が発生しました。入力の最後にカーソルを置かないと、入力の途中で何かを編集することはできません。また、「すべてを選択」することもできません。
キャレットの位置を取得してこのような処理を行うソリューションがあることは知っていますが、それらを自分のコードに統合する方法が本当にわかりません。
どうすればこれを行うことができますか?