JS script error - Canoot read property 'match'

0

Hello

This script is used to transform capital letters into small letters, keeping the first letter of capital letters.

But an error is occurring on line return str.match(/\S+\s*/g); :

Uncaught TypeError: Canoot read property 'match'

Follows script and follows error print:

$(window).load(function() {
    $.fn.capitalize = function() {
        //palavras para serem ignoradas
        var wordsToIgnore = ["DOS", "DAS", "de", "do"],
            minLength = 3;

        function getWords(str) {
            return str.match(/\S+\s*/g);
        }
        this.each(function() {
            var words = getWords(this.value);
            $.each(words, function(i, word) {
                // somente continua se a palavra nao estiver na lista de ignorados
                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();
                }
            });
            this.value = words.join("");
        });
    };

    //onblur do campo com classe .title
    $('.title').on('blur', function() {
        $(this).capitalize();
    }).capitalize();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><inputtype="text" id="txt_nome_fantasia" class="nome_fantasia title form-control input-sm" autocomplete="off" placeholder="Nome Fantasia" >

    
asked by anonymous 01.02.2018 / 19:08

1 answer

0

Simple, its getWords function is not receiving its parameter, so it does not initialize the str variable and since it is not initialized you can not use the .match method, proper of a string.

That's why the error writes, [...] Cannot read property 'match' of undefined.
Translated: [...] Não consegue ler a propriedade 'correspondência' de não definido

You should pass the parameter even if empty, for example if you pass "" as parameter its function would not return error, it would not find any match in your text and would return "" .

I recommend that you enter a breakpoint into:

   this.each(function() {
        var words = getWords(this.value);

And make sure this.value has a value. Home Unfortunately, we can not help you further, since neither your code nor your question reveals the assignment or purpose of the this.value variable, which is directly linked to the problem.

But one thing I can tell you:

  

The cause of your problem is that the variable passed as a parameter to getWords , in other words this.value is not started.

    
01.02.2018 / 19:34