DEV Community

Discussion on: Daily Challenge #219 - Compare Strings

Collapse
 
empereol profile image
Empereol

TypeScript

/**
 * Return the number of occurances of the search character in the target string.
 *
 * @param target String to search.
 * @param search Character to search string for.
 *
 * @throws {Error} If search params is not exactly one character.
 *
 * @example
 * strCount('Hello', 'o') // => 1
 * strCount('Hello', 'l') // => 2
 * strCount('', 'z')      // => 0
 */
function strCount(target: string, search: string): number {
  if (!search || search.length !== 1) {
    throw new Error('Search character be exactly one character');
  }

  return (target.match(new RegExp(search, 'g')) || []).length;
}