0
Hello,
With code below, I make the first letter of any word uppercase, except the words that are in the array wordsToIgnore
and wordContainAt
.
Now I thought to update the code and include an array called wordUpperCase
, where the words that are in this array will be completely uppercase.
Example: let wordUppercase = ['LTDA', 'S.A']
I tried to use the following if, but to no avail.
if (wordUpperCase.indexOf($.trim(word)) != -1) { words[i] = words[i].toUpperCase(); }
Below is the code along with an example
$(window).on('load', function() {
$.fn.capitalize = function() {
// words to ignore
let wordContainAt = '@',
wordsToIgnore = ['to', 'and', 'the', 'it', 'or', 'that', 'this', 'dos', 'rua', 'das', 'rh'],
minLength = 2;
function getWords(str) {
if (str == undefined) {
str = 'abc def';
} else {
str = str;
}
return str.match(/\S+\s*/g);
}
this.each(function() {
let words = getWords(this.value);
$.each(words, function(i, word) {
// only continues if the word is not in the ignore list or contains at '@'
if (word.indexOf(wordContainAt) != -1) {
words[i] = words[i].toLowerCase();
} else if (wordsToIgnore.indexOf($.trim(word)) == -1 && $.trim(word).length > minLength) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
} else {
words[i] = words[i].toLowerCase();
}
});
if (this.value != '') {
this.value = words.join('');
}
});
};
// field onblur with class .title
$(document).on('blur', '.lower', function() {
$(this).capitalize();
}).capitalize();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="lower">
Have this old post on SOPT talking about it who knows doesn’t help? https://answall.com/questions/224603/como-deixara-primeira-letra-mai%C3%Bascula
– Margot Paon Garcia