voca
Version:
The ultimate JavaScript string library
48 lines (41 loc) • 1.62 kB
JavaScript
import './internal/is_nil.js';
import './is_string.js';
import { c as coerceToString } from './internal/coerce_to_string.js';
import { R as REGEXP_UNICODE_CHARACTER } from './internal/const.js';
import { c as coerceToNumber } from './internal/coerce_to_number.js';
import { n as nanDefault } from './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 = coerceToString(subject);
var positionNumber = coerceToNumber(position);
var graphemeMatch;
var graphemeMatchIndex = 0;
positionNumber = nanDefault(positionNumber, 0);
while ((graphemeMatch = REGEXP_UNICODE_CHARACTER.exec(subjectString)) !== null) {
if (graphemeMatchIndex === positionNumber) {
REGEXP_UNICODE_CHARACTER.lastIndex = 0;
return graphemeMatch[0];
}
graphemeMatchIndex++;
}
return '';
}
export default graphemeAt;