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
3 Answers
Reset to default 4In 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>