简体   繁体   English

Javascript toLowerCase() 未定义错误

[英]Javascript toLowerCase() undefined error

I know this has been put out too many times, but none of the questions fix the problem I have.我知道这已经被提出了太多次,但没有一个问题能解决我遇到的问题。 It gives me the following error every time I run the function:每次运行 function 时都会出现以下错误:

TypeError: Cannot read property 'toLowerCase' of undefined

Here's the code it's running:这是它运行的代码:

global.toId = function(text) {
    return text.toLowerCase().replace(/[^a-z0-9]/g, '');
};

In ES2020, you can use optional chaining (?.)在 ES2020 中,您可以使用可选链接 (?.)

global.toId = function(text) {
    return text?.toLowerCase().replace(/[^a-z0-9]/g, '');
};

this help you : 这有助于你:

<!DOCTYPE html>
<html>
<head>
</head>

    <body>

        <script>

            var str = "EHSAN";

            var toId  = function(text) {

            return str.toLowerCase().replace(/[^a-z0-9]/g, '');

            }

           alert(toId());

        </script>

    </body>

</html>

You can add a protection with: 您可以添加以下保护:

if(typeof text === 'string')

In the function: 在功能中:

global.toId = function(text) {
   if(typeof text === 'string')
      return text.toLowerCase().replace(/[^a-z0-9]/g, '');
   else
      console.log('incorrect input');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript:TypeError 无法读取未定义的属性“toLowerCase”? - JavaScript: TypeError cant read property 'toLowerCase' of undefined? JavaScript - 无法读取未定义的属性“toLowerCase” - JavaScript - Cannot read property 'toLowerCase' of undefined 错误类型错误:keyword.toLowerCase 不是 function。(在“keyword.toLowerCase()”中,“keyword.toLowerCase”未定义) - ERROR TypeError: keyword.toLowerCase is not a function. (In 'keyword.toLowerCase()', 'keyword.toLowerCase' is undefined) 无法读取未定义的属性&#39;toLowerCase&#39;(Angularjs / JavaScript / Json) - Cannot read property 'toLowerCase' of undefined (Angularjs/JavaScript/Json) Angular 生产构建错误“无法读取未定义的属性'toLowerCase'中的错误” - Angular Production build error "ERROR in Cannot read property 'toLowerCase' of undefined" 我有错误未捕获的TypeError:无法读取未定义的属性&#39;toLowerCase&#39; - I have the error Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Angular 5:错误类型错误:无法读取未定义的属性“toLowerCase” - Angular 5 : ERROR TypeError: Cannot read property 'toLowerCase' of undefined TypeError:无法读取未定义的属性“ toLowerCase”,此错误总是重新运行 - TypeError: Cannot read property 'toLowerCase' of undefined this error always retrun 未捕获的TypeError:无法在文本字段上读取未定义错误的属性“ toLowerCase” - Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Error on text field 错误类型错误:无法读取 Pipe 未定义的属性“toLowerCase” - ERROR TypeError: Cannot read property 'toLowerCase' of undefined for Pipe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM