javascript - 如何在 String 对象的原型上实现这个测试?
问题描述
如何实现这个有效的功能?
我想实现一个返回true或false的测试函数,
示例:'any-string-1'.valid('!empty'):
这是我的 valid.js 文件
function valid(str) {
if (
typeof str == "undefined" ||
!str ||
str === "" ||
str.length < 10 ||
!/[^\s]/.test(str) ||
/^.*-s/i.test(str)
) {
return true;
} else if (str.length > 30) {
return false;
}
}
module.exports = valid;
解决方案
假设您使用的是 Jest,您可以使用toBe
:
const emptyStr = '';
const str = 'some-str';
expect(Boolean(emptyStr.length)).toBe(false); // it's empty, it's false because length is 0;
expect(str.length > 30).toBe(false); // it's false because length is not greather than 30;
expect(str.length < 10).toBe(true); // it's true because length is lower than 10;
推荐阅读
- discord.js - 如果我有自定义前缀,我如何成为私人用户
- r - 如何比较两个相同大小的组中的病例数?
- javascript - 如何拥有两个具有重复函数和变量的打字稿文件?
- c++ - 加载 DLL 会导致错误 193,即使它可以在 ctypes 和 JNA 中加载
- python - 如何在 Python 中对控制台输出进行空格填充?
- javascript - InnerHTML 没有更新?
- python - 如何获取帐户创建年龄 discord.py
- .htaccess - htaccess / mod_rewrite 命令用于创建硬编码的永久链接
- c# - 在 C# 中编写多线程映射 IEnumerator
- iis - IIS 请求过滤问题