最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript toLowerCase() undefined error - Stack Overflow

programmeradmin8浏览0评论

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:

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, '');
};

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:

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, '');
};
Share Improve this question edited Jun 15, 2016 at 14:09 Hopeful Llama 7585 silver badges26 bronze badges asked Jun 15, 2016 at 13:20 zellman01zellman01 331 gold badge1 silver badge3 bronze badges 3
  • 3 Its because variable text in your method is undefined. You should check for undefined, see this previous SO question: Detecting an undefined object property – Igor Commented Jun 15, 2016 at 13:22
  • Igor is correct. Where is the text parameter ing from when you call it? Can we see more of the code? – Hopeful Llama Commented Jun 15, 2016 at 13:23
  • 1 Check the invocation of toId function. You call it with undefined argument. – Constantine Commented Jun 15, 2016 at 13:24
Add a ment  | 

3 Answers 3

Reset to default 4

In ES2020, you can use optional chaining (?.)

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

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');
}

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>
发布评论

评论列表(0)

  1. 暂无评论