[英]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.