无法读取未定义错误的属性“匹配"

2022-01-19 00:00:00 reactjs frontend javascript html jsx

我试图在 React JS 前端显示一些文本来代替配置文件图像,当它不可用时.基本上,我将当前客户名称传递给一个函数,该函数提取名称中所有单词的第一个字符.我能够只显示名称,但是当我执行函数调用时,我收到无法读取未定义的属性匹配"错误并且页面未呈现.Console.log() 显示未定义.

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 the first characters of all the words in the name. I am able to display just the name but when I do a function call, I get Cannot read property 'match' of undefined" error and the page does not render. Console.log() displays undefined.

HTML:

<li className="nav-item">

               <div id="container_acronym">
                 <div id="name_acronym">                        
                    {this.acronym_name(this.state.lead_details.customer_name)}
                 </div>
                </div>                 
        </li>

JS:

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

推荐答案

 acronym_name(str){

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

        }
    }

相关文章