voca
Version:
The ultimate JavaScript string library
50 lines (42 loc) • 1.66 kB
JavaScript
;
require('./internal/is_nil.js');
require('./is_string.js');
var coerce_to_string = require('./internal/coerce_to_string.js');
var _const = require('./internal/const.js');
var coerce_to_number = require('./internal/coerce_to_number.js');
var nan_default = require('./internal/nan_default.js');
/**
* Get a grapheme from `subject` at specified `position` taking care of
* <a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#24surrogatepairs">surrogate pairs</a> and
* <a href="https://rainsoft.io/what-every-javascript-developer-should-know-about-unicode/#25combiningmarks">combining marks</a>.
*
* @function graphemeAt
* @static
* @since 1.0.0
* @memberOf Chop
* @param {string} [subject=''] The string to extract from.
* @param {number} position The position to get the grapheme.
* @return {string} Returns the grapheme at specified position.
* @example
* v.graphemeAt('\uD835\uDC00\uD835\uDC01', 0); // or '𝐀𝐁'
* // => 'A'
*
* v.graphemeAt('cafe\u0301', 3); // or 'café'
* // => 'é'
*/
function graphemeAt(subject, position) {
var subjectString = coerce_to_string.coerceToString(subject);
var positionNumber = coerce_to_number.coerceToNumber(position);
var graphemeMatch;
var graphemeMatchIndex = 0;
positionNumber = nan_default.nanDefault(positionNumber, 0);
while ((graphemeMatch = _const.REGEXP_UNICODE_CHARACTER.exec(subjectString)) !== null) {
if (graphemeMatchIndex === positionNumber) {
_const.REGEXP_UNICODE_CHARACTER.lastIndex = 0;
return graphemeMatch[0];
}
graphemeMatchIndex++;
}
return '';
}
module.exports = graphemeAt;