3

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, '');
};
Hopeful Llama
  • 728
  • 5
  • 26
zellman01
  • 33
  • 1
  • 1
  • 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](http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) – Igor Jun 15 '16 at 13:22
  • Igor is correct. Where is the `text` parameter coming from when you call it? Can we see more of the code? – Hopeful Llama Jun 15 '16 at 13:23
  • 1
    Check the invocation of toId function. You call it with undefined argument. – Constantine Jun 15 '16 at 13:24

3 Answers3

4

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

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

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>
Ehsan
  • 12,655
  • 3
  • 25
  • 44
0

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