1

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

I'm having trouble refactoring the code made in jQuery toVannila JS, 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 ?

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" />

Vannila JS Syntax example

const capitalizeTheWord = () => {

    console.log('hello World');
    const inputWordCapitalize = document.querySelector('input.lower');
    inputWordCapitalize.addEventListener('blur', (e) => {
        //
    });
};

export default capitalizeTheWord();
Barmar
  • 741,623
  • 53
  • 500
  • 612
The100
  • 66
  • 7
  • 2
    Converting jQuery to vanilla JS is independent of exporting. Work on one thing at a time. – Barmar Mar 20 '20 at 16:52
  • 1
    See https://stackoverflow.com/questions/978799/is-there-an-easy-way-to-convert-jquery-code-to-javascript for resources on converting JQ to JS. – Barmar Mar 20 '20 at 16:52

0 Answers0