Last active
November 23, 2020 23:01
-
-
Save matiaslopezd/4257859e3c183563d32d99d302d42bd1 to your computer and use it in GitHub Desktop.
Count characters in DOM element with case sensitive option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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