awesome-string
Version:
The ultimate JavaScript string library
39 lines (38 loc) • 1.52 kB
JavaScript
import coerceToNumber from 'helper/number/coerce_to_number';
import coerceToString from 'helper/string/coerce_to_string';
import nanDefault from 'helper/number/nan_default';
import { REGEXP_UNICODE_CHARACTER } from 'helper/reg_exp/const';
/**
* 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
* as.graphemeAt('\uD835\uDC00\uD835\uDC01', 0); // or '𝐀𝐁'
* // => 'A'
*
* as.graphemeAt('cafe\u0301', 3); // or 'café'
* // => 'é'
*/
export default function graphemeAt(subject, position) {
const subjectString = coerceToString(subject);
let positionNumber = coerceToNumber(position);
let graphemeMatch;
let 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 '';
}