Quickjs.StringJavaScript 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.
This library follows JavaScript semantics in most cases to ensure compatibility with the ECMA-262 specification:
index_of return -1 when not found (JavaScript convention), not option (OCaml convention). This matches JavaScript's String.prototype.indexOf().char_code_at return int option (OCaml convention) for bounds checking, since OCaml does not have JavaScript's implicit NaN coercion.slice support negative indices counting from the end, matching JavaScript behavior.Invalid_argument on invalid patterns, mirroring the SyntaxError JavaScript throws for invalid regular expression literals.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).
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.
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.
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).
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.
module Prototype : sig ... endString.prototype methods
lowercase_char c converts a single character to lowercase. May return multiple characters for special cases.