insert method
Returns a new string with newChar inserted at the specified position.
position is a grapheme-cluster index (user-perceived characters), so
an insert never lands inside an emoji or between a letter and its
combining mark. Returns the original string if position is out of
bounds (negative or greater than the grapheme count).
Example:
'ac'.insert('b', 1); // 'abc'
'👋c'.insert('b', 1); // '👋bc'
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String insert(String newChar, int position) {
// Bound by grapheme count, not code-unit `length`: the slices below are
// grapheme-indexed (substringSafe), so a code-unit bound let positions past
// the last grapheme through and silently appended instead of rejecting.
if (position < 0 || position > characters.length) {
return this;
}
return substringSafe(0, position) + newChar + substringSafe(position);
}