Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→string-convert-indexesnext

string-convert-indexes6.2.1

Convert between native JS string character indexes and grapheme-count-based indexes

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • IDEA
  • API — NATIVETOUNIC…
  • API — UNICODETONAT…
  • API — VERSION
  • Changelog

Installation

Quick Take

Examples

  • Convert the indexes within a plain object
  • Convert an array of native indexes
  • Convert a single native index
  • Convert the indexes within a nested structure
  • Throw on an out-of-range Unicode index
  • Convert the indexes there and back
  • Convert Unicode indexes into native ones
  • Index a zero-width-joiner emoji sequence

Idea

Native JS string index system is not based on grapheme count — while “a” length is one, emoji “🧢” is two-character-long, because it’s two characters actually, \uD83E and \uDDE2.

In ideal world, JS string index system would count emoji as one character-long. That’s so-called grapheme-based index system. Letter “a” and cap emoji “🧢” are both graphemes.

This program is a converter that converts between the two systems, it’s based on grapheme-splitteropens in a new tab.

API — nativeToUnicode()

It converts JS native indexes to indexes (used in let’s say String.slice()), based on grapheme count.

The function nativeToUnicode() is imported like this:

It’s a function which takes two input arguments:

Input argumentTypeObligatoryDescription
str
Type: String
Obligatory: yes
strStringyesThe string in which you want to perform a search
indexes
Type: Whatever
Obligatory: yes
indexesWhateveryesNormally a natural number or zero but it can be numeric string or nested AST of thereof.

The function will return a clone of the same data structure as indexes, but with digits converted.

API — unicodeToNative()

It converts grapheme count-based indexes to JS native indexes.

The function unicodeToNative() is imported like this:

It’s a function which takes two input arguments:

Input argumentTypeObligatoryDescription
str
Type: String
Obligatory: yes
strStringyesThe string in which you want to perform a search
indexes
Type: Whatever
Obligatory: yes
indexesWhateveryesNormally a natural number or zero but it can be numeric string or nested AST of thereof.

The function will return a clone of the same data structure as indexes, but with digits converted.

API — version

You can import version:

Changelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab