我有字符串:
const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';
如何检查这个字符串是否恰好包含五个@?
我可以检查字符串是否包含一个@:
expect(hash).to.include('@');
您可以计算出现次数,然后验证计数:
const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';
const count = (hash.match(/@/g) || []).length;
expect(count).to.equal(5);
let isValid = 0
for (let i = 0; i < hash.length; i++) {
if (hash.includes("@", i)){
isValid++;
if(isValid === 5) {
// do something (true)
}
} else {
// do something (false)
}
}
您可以使用
.to.match()
:
const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';
expect(hash).to.match(/^(?:[^@]*@[^@]*){5}$/g);
或:
expect(hash.replace(/[^@]/g, "")).to.eq("@@@@@");