Last active
June 19, 2016 00:45
-
-
Save theftprevention/28cc468c761f985087d8df17db7c3265 to your computer and use it in GitHub Desktop.
Defines the "charCount" method, which returns the number of characters in a string. Assumes that the browser / environment supports the ECMAScript 6 String.prototype.codePointAt() method (IE 11+).
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
(function (window) { | |
'use strict'; | |
var charCodeAt, codePointAt; | |
if (!window.charCount) { | |
charCodeAt = String.prototype.charCodeAt; | |
codePointAt = String.prototype.codePointAt; | |
/** | |
* Determines the number of characters present in a string. Accounts for the | |
* presence of any UTF-16 surrogate pairs, and counts them as a single | |
* character (as opposed to String.prototype.length, which counts them as 2). | |
* | |
* @param {string} str The string whose characters will be counted. | |
* @returns {number} The number of characters in the string. | |
*/ | |
function charCount(str) { | |
var s = String(str), | |
l = s.length, | |
i = r = 0; | |
for (i, l; i < l; i++) { | |
if (charCodeAt.call(s, i) === codePointAt.call(s, i)) { | |
r++; | |
} | |
} | |
return r; | |
} | |
window.charCount = charCount; | |
} | |
})(self); |
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
(function(T,h,e,f,t,s){'use strict';var v=h.prototype,C=v[f],P=v[t];if(!T[e])T[e]=function(m){var r=0,i=0,S=h(m),l=S.length;for(i,l;i<l;i++){C[s](S,i)===P[s](S,i)&&r++;}return r;};})(window,String,'charCount','charCodeAt','codePointAt','call'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment