Skip to content

Instantly share code, notes, and snippets.

@theftprevention
Last active June 19, 2016 00:45
Show Gist options
  • Save theftprevention/28cc468c761f985087d8df17db7c3265 to your computer and use it in GitHub Desktop.
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+).
(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);
(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