Module Quickjs.String

JavaScript String built-in object

This module mirrors the JavaScript String API with prototype methods for string manipulation. All methods use UTF-16 semantics for indices.

JavaScript vs OCaml Semantics

This library follows JavaScript semantics in most cases to ensure compatibility with the ECMA-262 specification:

type normalization =
  1. | NFC
  2. | NFD
  3. | NFKC
  4. | NFKD

Unicode normalization forms

val is_valid_utf8 : string -> bool

is_valid_utf8 s returns true if s contains only valid UTF-8 byte sequences. Use this for strict validation before processing untrusted input.

Note: All functions in this module handle invalid UTF-8 gracefully by replacing malformed sequences with U+FFFD (replacement character).

val utf16_index_of_byte : string -> int -> int

utf16_index_of_byte s i converts a UTF-8 byte offset in s into the corresponding UTF-16 code unit index (the unit used by every index in this module and in RegExp). Offsets falling inside a multi-byte sequence map to the index of that character; out-of-range offsets are clamped. Useful at the boundary with byte-oriented code.

val byte_index_of_utf16 : string -> int -> int

byte_index_of_utf16 s i converts a UTF-16 code unit index into the corresponding UTF-8 byte offset in s. Indices falling inside a surrogate pair map to the byte offset of that character; out-of-range indices are clamped. Inverse of utf16_index_of_byte.

Static methods

val from_char_code : int array -> string

from_char_code codes builds a string from UTF-16 code units. Every value is coerced with ToUint16 (kept modulo 216, so from_char_code [| 0x10041 |] is "A") and adjacent high/low surrogate values combine into one code point: from_char_code [| 0xD83D; 0xDE00 |] is "😀". Equivalent to JavaScript's String.fromCharCode().

Unpaired surrogates become U+FFFD, since UTF-8 cannot represent them (JavaScript builds a lone-surrogate string instead).

val from_code_point : int array -> string

from_code_point code_points builds a string from Unicode code points: from_code_point [| 0x1F600 |] is "😀". Equivalent to JavaScript's String.fromCodePoint().

Surrogate halves given as separate code points pair up exactly like in JavaScript (from_code_point [| 0xD83D; 0xDE00 |] is also "😀"); unpaired surrogates become U+FFFD, since UTF-8 cannot represent them.

  • raises Invalid_argument

    if any value is outside 0..0x10FFFF, mirroring the RangeError JavaScript throws.

module Prototype : sig ... end

String.prototype methods

val lowercase_char : Uchar.t -> Uchar.t list

lowercase_char c converts a single character to lowercase. May return multiple characters for special cases.

val uppercase_char : Uchar.t -> Uchar.t list

uppercase_char c converts a single character to uppercase. May return multiple characters (e.g., ß -> SS).