Skip to content Skip to sidebar Skip to footer

Cannot Read Property 'match' Of Undefined Error

I am trying to display some text in React JS frontend in place of a profile image when it isn't available.Basically, I pass the current customer name to a function which extracts t

Solution 1:

this.state.lead_details.customer_name seems undefined, so you need to catch that case.

You have multiple ways of doing this, if you use babel this declaration with default value should work:

acronym_name(str = ''){
    var regular_ex=/\b(\w)/g;
    var matches = str.match(regular_ex);
    var acronym = matches.join('');
    document.getElementById("name_acronym").innerHTML = acronym;
}

Otherwise you can also check inside the function if undefined was given:

acronym_name(str){
    if (typeof str == 'undefined') {
        str = '';
    }
    var regular_ex=/\b(\w)/g;
    var matches = str.match(regular_ex);
    var acronym = matches.join('');
    document.getElementById("name_acronym").innerHTML = acronym;
}

Lastly you could in some way prevent giving undefined to the function in the first place. For example like this:

<li className="nav-item">
    <div id="container_acronym">
        <div id="name_acronym">                        
           {this.acronym_name(this.state.lead_details.customer_name || '')}
        </div>
    </div>                 
</li>

Solution 2:

acronym_name(str){

        if (typeof str == 'undefined') {   
            str = '';
        }
        else{ 
            var regular_ex=/\b(\w)/g;
            var matches = str.match(regular_ex);
            var acronym = matches.join('');
            return acronym;

        }
    }

Post a Comment for "Cannot Read Property 'match' Of Undefined Error"