Skip to content

Instantly share code, notes, and snippets.

@matiaslopezd
Last active November 23, 2020 23:01
Show Gist options
  • Save matiaslopezd/4257859e3c183563d32d99d302d42bd1 to your computer and use it in GitHub Desktop.
Save matiaslopezd/4257859e3c183563d32d99d302d42bd1 to your computer and use it in GitHub Desktop.
Count characters in DOM element with case sensitive option
/**
* Search number of times a character/string exist in DOM element
*
* @name countCharacter
* @param DOMElement {String|Object} - DOM element you want count characters inside
* @param character {String} - String you want count
* @param caseSensitive {Boolean} - Option to set sensitive to uppercase or lowercase
* @return {Number} - Total of times character match in DOM element
**/
function countCharacter(DOMElement = 'body', character = '', caseSensitive = false) {
const element = (typeof DOMElement === 'string') ? document.querySelector(DOMElement) : DOMElement;
const text = element.innerText;
const option = caseSensitive ? 'g' : 'gi';
return text.match(new RegExp(character, option)).length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment