如果字符串包含五个@,如何通过 chai 检查?

问题描述 投票:0回答:3

我有字符串:

const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';

如何检查这个字符串是否恰好包含五个@?

我可以检查字符串是否包含一个@:

expect(hash).to.include('@');
javascript chai
3个回答
3
投票

您可以计算出现次数,然后验证计数:

const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';
const count = (hash.match(/@/g) || []).length;
expect(count).to.equal(5);

2
投票
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)
    }
}

0
投票

您可以使用

.to.match()

const hash = 'dwqdiojqwoidj@2323joij@oindoi2d@dndi2on@diodno@1';
expect(hash).to.match(/^(?:[^@]*@[^@]*){5}$/g);

或:

expect(hash.replace(/[^@]/g, "")).to.eq("@@@@@");
© www.soinside.com 2019 - 2024. All rights reserved.