DEV Community

Wagner Fillio
Wagner Fillio

Posted on

jQuery to VannilaJS (export function using ES6)

Hi, This script transforms the first letter of each word into a capital letter, except for some words that are part of the arrays of the variables wordContainAt, wordsToIgnore, wordUpperCase.

I'm having trouble refactoring a code made in jQuery toJavascript Vannila, using the ES6 export.

I think I didn't understand this concept very well, besides not being able to get the this object, within the scope of the function.

Can someone help me ?


javascript
$(window).on('load', function() {
    $.fn.capitalize = function() {
        // words to ignore
        let wordContainAt = '@',
            wordsToIgnore = ['to', 'and', 'the', 'it', 'or', 'that', 'this', 'dos', 'rua-', 'das', 'rh', 'r'],
            wordUpperCase = ['LTDA', 'S.A', 'S.A.', 'SMS', 'LJ', 'CS', 'II'],
            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();
});


/// I need help in this code below
const capitalizeTheWord = () => {
    console.log('teste');
    const inputWordCapitalize = document.querySelector('input.word-capitalize');
    inputWordCapitalize.addEventListener('keypress', (e) => {
        // more code
    });
};
export default capitalizeTheWord();

Top comments (0)