Search code examples
javascriptchai

How to expect that a string contains exactly N of a particular character in Chai?


I have string:

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

How can I check if this string contains exactly five @ characters?

I can check if string contains one @:

expect(hash).to.include('@');

Solution

  • You can count occurrences and then verify the count instead:

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