Reputation: 33
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, '');
};
Upvotes: 3
Views: 13353
Reputation: 71
In ES2020, you can use optional chaining (?.)
global.toId = function(text) {
return text?.toLowerCase().replace(/[^a-z0-9]/g, '');
};
Upvotes: 4
Reputation: 12969
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>
Upvotes: 0
Reputation: 38
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');
}
Upvotes: 0