Skip to content

Instantly share code, notes, and snippets.

@iambenkay
Created April 17, 2020 23:32
Show Gist options
  • Save iambenkay/0bc5ccd1c5a61db82ee2aa9d11de2aab to your computer and use it in GitHub Desktop.
Save iambenkay/0bc5ccd1c5a61db82ee2aa9d11de2aab to your computer and use it in GitHub Desktop.
Count Characters
<h1>The 'B' counter</h1>
<input placeholder="string to search" />
<button>Count</button>
<div c></div>
const button = document.querySelector("button");
const input = document.querySelector("input");
button.addEventListener('click', () => {
const count = countBs(input.value);
document.querySelector("[c]").innerHTML = `B occurred ${count} times`;
});
const countBs = (str) => countChar(str, 'B');
const countChar = (str, c) => (str.match(new RegExp(`${c}`, 'g')) || []).length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment