1
This script capitalizes the first letter of each word, except for a few words that are part of the matrices in the variables wordContainAt, wordsToIgnore, wordUpperCase
.
I’m having trouble refactoring the code created on jQuery
for JavaScript Puro
. I intend to use módulos de exportação ES6
.
I know that export has nothing to do with function, but in this context, I don’t think I understand very well the concept of a função anônima
, or arrow function
, because I can’t get the object this
within the scope of the function, as in jQuery.
Can someone help me ?
jQuery
$(window).on('load', function() {
$.fn.capitalize = function() {
// words to ignore
let wordContainAt = '@',
wordsToIgnore = ['to', 'and', 'the', 'it', 'or', 'that', 'this'],
wordUpperCase = ['S.A', 'SMS', 'USA'],
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);
console.log(words);
$.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 (wordUpperCase.indexOf($.trim(word).toUpperCase()) != -1) {
words[i] = words[i].toUpperCase();
} 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 .lower
$(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 class="lower" />
Javascript example
const capitalizeTheWord = () => {
constole.log(this) // undefined
const inputWordCapitalize = document.querySelector('input.lower');
inputWordCapitalize.addEventListener('blur', (e) => {
// capitalizeTheWord...
});
};
export default capitalizeTheWord();