Skip to content

Strings ​

string is the native UTF-8 text type in tyrus. Source syntax is concise and statically checked, while the runtime implementation is native.

Quoted Strings ​

tyrus
const greeting: string = "hello";
const alternative: string = 'hello';

The formatter normalizes quotes according to quote_style, unless it is set to "off", which preserves the original quotes and escapes of every string literal.

Multiline Strings ​

A string delimited by """ can span multiple lines while staying aligned with the surrounding code. The compiler dedents it at compile time: from every line, it strips as many leading spaces as the closing """ itself is indented with, and it drops a first line left blank right after the opening """. The result is an ordinary string literal, so there is no runtime cost to writing an aligned query or template instead of one flush against the left margin.

tyrus
const query: string = """
    SELECT id, name
    FROM users
    WHERE active = true
    """;

The dedent margin only counts spaces; a """ closed on a tab-indented line measures a margin of zero, so use spaces for the indentation you want stripped.

Template Literals ​

Use template literals for interpolation and multiline text.

tyrus
const name: string = "Ada";
const greeting: string = `Hello, ${name}`; // Hello, Ada

const message: string = `line one
line two`;

const pi: f64 = 3.141592;
const id: i32 = 42;
const status: string = `Value: ${pi:.2f} | Code: ${id:04d}`; // Value: 3.14 | Code: 0042

An interpolation may carry a format specifier after :, .Nf fixes a float to exactly N decimal places, and 0Nd zero-pads an integer to a total width of N characters. .Nf requires a float value and 0Nd requires an integer value; a mismatch is a compile error (E0717) naming the required kind.

A union-typed value may be interpolated too. Which variant it holds is a run-time fact, so the rendering is chosen at run time and matches what print would print for that variant.

Literal String Types ​

String literals can participate in literal unions and tagged unions.

A literal union is an ordinary value: compare it with any of its variants (status === "active"), branch on it with a match that needs no _ when it covers every variant, build one with a ternary, collect them in an array, and call on it anything a string accepts, every variant of a string-literal union is a string. The comparison is a single byte check rather than a text comparison, because such a union is represented by which variant it holds and nothing else.

tyrus
type Role = "admin" | "operator" | "viewer";

interface Success {
    tag: "success";
    data: string;
}

Literal values are not enum members

Use literal strings for small closed text domains. Use enum when the domain needs named members and native enum semantics.

Grapheme clusters ​

chars() gives Unicode scalar values; graphemes() gives what a reader calls characters. They differ wherever one visible character is written with several scalar values, an emoji built from a zero-width joiner sequence, or a letter followed by a combining accent.

tyrus
const astronaut: string = "👨‍🚀";

print(astronaut.chars().length);      // 3
print(astronaut.graphemes().length);  // 1

Indexing, slicing and length count scalar values, not clusters: that is the unit every position in the string API is measured in, and it is what makes text.charAt(text.length - 1) the last one. graphemes() is the answer to the display question, how many characters a reader sees, and where a cursor would stop, and it returns string[], because a cluster can hold more than one scalar value.

String Properties ​

length ​

tyrus
const message: string = "tyrus";
const count: usize = message.length; // 5

const accented: string = "héllo";
const characters: usize = accented.length; // 5 characters, not 6 bytes

const launch: string = "a🚀b";
const positions: usize = launch.length; // 3, one position per character

length is read from the value, not counted: a string carries its character count alongside its text, so asking for it costs the same whether the string holds three characters or three million. U+0000 is an ordinary character in a string, the text is delimited by its recorded length, not by a terminator, so "a\u{0}b".length is 3 and the whole of it survives comparison, interpolation and printing.

length counts characters, Unicode scalar values, never the underlying UTF-8 bytes, so it agrees with chars() on any text. Every position in the string API is measured in that same unit: charAt(), charCodeAt(), slice(), substring(), indexOf(), lastIndexOf(), padStart() and padEnd() all count characters, which is what makes text.charAt(text.length - 1) the last character of any string, accented or not.

Methods ​

CategoryMethods
Case conversiontoUpperCase(), toLowerCase()
Case transformationtoSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase()
Trimmingtrim(), trimStart(), trimEnd()
Searchingincludes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search()
Slicing & extractingslice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis()
Transformingreplace(), repeat(), padStart(), padEnd(), concat(), split()
HTML & encodingstripHtml(), escapeHtml(), urlEncode(), urlDecode()
Pattern matchingmatch(), matchAll()
Iterationchars(), graphemes()

Case conversion ​


toUpperCase() ​

Returns the string with all uppercase characters.

SignaturetoUpperCase(): string
tyrus
const shout: string = "tyrus";
const loud: string = shout.toUpperCase(); // TYRUS

error

tyrus
const flag: boolean = true;
const upper: string = flag.toUpperCase(); 
text
error[E0599]: no method named `toUpperCase` for type `boolean`
at /src/main.tyr:2:23
const upper: string = flag.toUpperCase();
                      ^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

toLowerCase() ​

Returns the string with all lowercase characters.

SignaturetoLowerCase(): string
tyrus
const shout: string = "TYRUS";
const quiet: string = shout.toLowerCase(); // "tyrus"

error

tyrus
const flag: boolean = true;
const lower: string = flag.toLowerCase(); 
text
error[E0599]: no method named `toLowerCase` for type `boolean`
at /src/main.tyr:2:23
const lower: string = flag.toLowerCase();
                      ^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

Case transformation ​


toSlugCase() ​

Normalizes the string into a URL-friendly slug. Strips accents via NFKD decomposition, removes non-alphanumeric characters, and joins words with hyphens.

SignaturetoSlugCase(): string
tyrus
const title: string = "Como criar uma API em Tyrus!";
const slug: string = title.toSlugCase(); // "como-criar-uma-api-em-tyrus"

const greeting: string = "Hällo Wörld";
const clean: string = greeting.toSlugCase(); // "hallo-world"

error

tyrus
const flag: boolean = true;
const slug: string = flag.toSlugCase(); 
text
error[E0599]: no method named `toSlugCase` for type `boolean`
at /src/main.tyr:2:22
const slug: string = flag.toSlugCase();
                     ^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

toDashCase() ​

Converts the string to dash-case (lowercase words joined by hyphens). Tokenizes on whitespace, underscores, hyphens and camelCase boundaries. Unlike toSlugCase(), accents are preserved.

SignaturetoDashCase(): string
tyrus
const phrase: string = "hello world example";
const dashed: string = phrase.toDashCase(); // "hello-world-example"

const camel: string = "HelloWorldExample";
const result: string = camel.toDashCase(); // "hello-world-example"

error

tyrus
const flag: boolean = true;
const dashed: string = flag.toDashCase(); 
text
error[E0599]: no method named `toDashCase` for type `boolean`
at /src/main.tyr:2:24
const dashed: string = flag.toDashCase();
                       ^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

toKebabCase() ​

Alias for toDashCase().

SignaturetoKebabCase(): string
tyrus
const phrase: string = "hello world example";
const kebab: string = phrase.toKebabCase(); // "hello-world-example"

toKebabCase() is an alias for toDashCase().


toPascalCase() ​

Converts the string to PascalCase. Each word is capitalized and joined without separators.

SignaturetoPascalCase(): string
tyrus
const phrase: string = "hello world example";
const pascal: string = phrase.toPascalCase(); // "HelloWorldExample"

const snake: string = "hello_world_example";
const result: string = snake.toPascalCase(); // "HelloWorldExample"

error

tyrus
const flag: boolean = true;
const pascal: string = flag.toPascalCase(); 
text
error[E0599]: no method named `toPascalCase` for type `boolean`
at /src/main.tyr:2:24
const pascal: string = flag.toPascalCase();
                       ^^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

toCamelCase() ​

Converts the string to camelCase. The first word is lowercase, subsequent words are capitalized.

SignaturetoCamelCase(): string
tyrus
const phrase: string = "hello world example";
const camel: string = phrase.toCamelCase(); // "helloWorldExample"

const pascal: string = "HelloWorldExample";
const result: string = pascal.toCamelCase(); // "helloWorldExample"

error

tyrus
const flag: boolean = true;
const camel: string = flag.toCamelCase(); 
text
error[E0599]: no method named `toCamelCase` for type `boolean`
at /src/main.tyr:2:23
const camel: string = flag.toCamelCase();
                      ^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

toSnakeCase() ​

Converts the string to snake_case (lowercase words joined by underscores).

SignaturetoSnakeCase(): string
tyrus
const phrase: string = "hello world example";
const snake: string = phrase.toSnakeCase(); // "hello_world_example"

const camel: string = "HelloWorldExample";
const result: string = camel.toSnakeCase(); // "hello_world_example"

error

tyrus
const flag: boolean = true;
const snake: string = flag.toSnakeCase(); 
text
error[E0599]: no method named `toSnakeCase` for type `boolean`
at /src/main.tyr:2:23
const snake: string = flag.toSnakeCase();
                      ^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

Trimming ​


trim() ​

Removes whitespace from both ends of the string.

Signaturetrim(): string
tyrus
const padded: string = "  hello  ";
const clean: string = padded.trim(); // "hello"

error

tyrus
const value: i32 = 42;
const clean: string = value.trim(); 
text
error[E0599]: no method named `trim` for type `i32`
at /src/main.tyr:2:23
const clean: string = value.trim();
                      ^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

trimStart() ​

Removes whitespace from the start of the string.

SignaturetrimStart(): string
tyrus
const padded: string = "  hello  ";
const left: string = padded.trimStart(); // "hello  "

error

tyrus
const value: i32 = 42;
const left: string = value.trimStart(); 
text
error[E0599]: no method named `trimStart` for type `i32`
at /src/main.tyr:2:22
const left: string = value.trimStart();
                     ^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

trimEnd() ​

Removes whitespace from the end of the string.

SignaturetrimEnd(): string
tyrus
const padded: string = "  hello  ";
const right: string = padded.trimEnd(); // "  hello"

error

tyrus
const value: i32 = 42;
const right: string = value.trimEnd(); 
text
error[E0599]: no method named `trimEnd` for type `i32`
at /src/main.tyr:2:23
const right: string = value.trimEnd();
                      ^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

Searching ​


includes() ​

Checks if the string contains a substring.

Signatureincludes(search: string): boolean
tyrus
const sentence: string = "tyrus is native";
const found: boolean = sentence.includes("native"); // true

error

tyrus
const sentence: string = "tyrus is native";
const found: boolean = sentence.includes(42); 
text
error[E0308]: type mismatch for `includes`: expected `string`, found `integer literal`
at /src/main.tyr:2:24
const found: boolean = sentence.includes(42);
                       ^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

startsWith() ​

Checks if the string starts with a substring.

SignaturestartsWith(search: string): boolean
tyrus
const filename: string = "main.tyr";
const isSource: boolean = filename.startsWith("main."); // true

error

tyrus
const filename: string = "main.tyr";
const isSource: boolean = filename.startsWith(true); 
text
error[E0308]: type mismatch for `startsWith`: expected `string`, found `boolean`
at /src/main.tyr:2:27
const isSource: boolean = filename.startsWith(true);
                          ^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

endsWith() ​

Checks if the string ends with a substring.

SignatureendsWith(search: string): boolean
tyrus
const filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(".tyr"); // true

error

tyrus
const filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(42); 
text
error[E0308]: type mismatch for `endsWith`: expected `string`, found `integer literal`
at /src/main.tyr:2:26
const isTyrus: boolean = filename.endsWith(42);
                         ^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

indexOf() ​

Returns the index of the first occurrence of a substring, or -1.

SignatureindexOf(search: string, start?: i64): i64
tyrus
const text: string = "hello world";
const position: i64 = text.indexOf("world"); // 6
const missing: i64 = text.indexOf("rust"); // -1

error

tyrus
const text: string = "hello world";
const position: i64 = text.indexOf(["hello"]); 
text
error[E0308]: type mismatch for `indexOf`: expected `string`, found `string[]`
at /src/main.tyr:2:23
const position: i64 = text.indexOf(["hello"]);
                      ^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

lastIndexOf() ​

Returns the index of the last occurrence of a substring, or -1.

SignaturelastIndexOf(search: string, start?: i64): i64
tyrus
const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf("/"); // 3

error

tyrus
const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf(42); 
text
error[E0308]: type mismatch for `lastIndexOf`: expected `string`, found `integer literal`
at /src/main.tyr:2:24
const lastSlash: i64 = path.lastIndexOf(42);
                       ^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Searches for a pattern using a regular expression and returns the index of the match.

Signaturesearch(pattern: Regex): i64
tyrus
const main = (): void => {
    const email: string = "[email protected]";
    const atSign: i32 = email.search(/@/); // 4
    print(atSign); // 4
};

error

tyrus
const main = (): void => {
    const email: string = "[email protected]";
    const atSign: i32 = email.search("@"); 
};
text
error[E0308]: type mismatch for `search`: expected `Regex`, found `string`
at /src/main.tyr:3:25
    const atSign: i32 = email.search("@"); // [!code error]
                        ^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Slicing and extracting ​


slice() ​

Extracts a section of the string and returns it as a new string.

Signatureslice(start?: i64, end?: i64): string
tyrus
const code: string = "tyrus-lang";
const lang: string = code.slice(6); // "lang"
const sub: string = code.slice(0, 5); // "tyrus"

error

tyrus
const code: string = "tyrus-lang";
const result: string = code.slice("6"); 
text
error[E0308]: type mismatch for `slice`: expected `i64`, found `string`
at /src/main.tyr:2:24
const result: string = code.slice("6");
                       ^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

substring() ​

Returns a substring starting at a given index.

Signaturesubstring(start: i64, end?: i64): string
tyrus
const version: string = "v0.1.0";
const numeric: string = version.substring(1); // "0.1.0"

error

tyrus
const version: string = "v0.1.0";
const numeric: string = version.substring("1"); 
text
error[E0308]: type mismatch for `substring`: expected `i64`, found `string`
at /src/main.tyr:2:25
const numeric: string = version.substring("1");
                        ^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

charAt() ​

Returns the character at a specified index.

SignaturecharAt(index: i64): string
tyrus
const word: string = "tyrus";
const letter: string = word.charAt(0); // "t"

error

tyrus
const word: string = "tyrus";
const letter: string = word.charAt("0"); 
text
error[E0308]: type mismatch for `charAt`: expected `usize`, found `string`
at /src/main.tyr:2:24
const letter: string = word.charAt("0");
                       ^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

charCodeAt() ​

Returns the Unicode code point of the character at a specified index.

SignaturecharCodeAt(index: i64): u32
tyrus
const main = (): void => {
    const letter: string = "A";
    const code: i32 = letter.charCodeAt(0); // 65
    print(code); // 65
};

error

tyrus
const main = (): void => {
    const letter: string = "A";
    const code: i32 = letter.charCodeAt("0"); 
};
text
error[E0308]: type mismatch for `charCodeAt`: expected `usize`, found `string`
at /src/main.tyr:3:23
    const code: i32 = letter.charCodeAt("0"); // [!code error]
                      ^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

truncate() ​

Truncates the string to a maximum number of code points.

Signaturetruncate(maxLength: i64): string
tyrus
const text: string = "Hello, World!";
const short: string = text.truncate(5); // "Hello"
const small: string = text.truncate(3); // "Hel"

error

tyrus
const text: string = "hello";
const bad: string = text.truncate("ten"); 
text
error[E0308]: type mismatch for `truncate`: expected `usize`, found `string`
at /src/main.tyr:2:21
const bad: string = text.truncate("ten");
                    ^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

truncateEllipsis() ​

Truncates the string to a maximum number of code points and appends ... when the text overflows.

SignaturetruncateEllipsis(maxLength: i64): string
tyrus
const text: string = "Hello, World!";
const short: string = text.truncateEllipsis(8); // "Hello..."
const fits: string = "hello".truncateEllipsis(10); // "hello"

error

tyrus
const text: string = "hello";
const bad: string = text.truncateEllipsis("ten"); 
text
error[E0308]: type mismatch for `truncateEllipsis`: expected `usize`, found `string`
at /src/main.tyr:2:21
const bad: string = text.truncateEllipsis("ten");
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Transforming ​


replace() ​

Replaces a substring or pattern with a replacement string.

Signaturereplace(search: string | Regex, replacement: string): string
tyrus
const path: string = "src/main.ts";
const updated: string = path.replace(".ts", ".tyr"); // "src/main.tyr"

error

tyrus
const path: string = "src/main.ts";
const updated: string = path.replace(".ts", 42); 
text
error[E0308]: type mismatch for `replace`: expected `string`, found `integer literal`
at /src/main.tyr:2:25
const updated: string = path.replace(".ts", 42);
                        ^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

repeat() ​

Returns a new string with the original repeated a given number of times.

Signaturerepeat(count: i64): string
tyrus
const divider: string = "-".repeat(20); // "--------------------"
const pattern: string = "ab".repeat(3); // "ababab"

error

tyrus
const divider: string = "-".repeat("20"); 
text
error[E0308]: type mismatch for `repeat`: expected `usize`, found `string`
at /src/main.tyr:1:25
const divider: string = "-".repeat("20");
                        ^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

padStart() ​

Pads the start of the string with a filler string to reach a target length.

SignaturepadStart(targetLength: i64, fill?: string): string
tyrus
const id: string = "42";
const padded: string = id.padStart(5, "0"); // "00042"

error

tyrus
const id: string = "42";
const padded: string = id.padStart("5"); 
text
error[E0308]: type mismatch for `padStart`: expected `usize`, found `string`
at /src/main.tyr:2:24
const padded: string = id.padStart("5");
                       ^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

padEnd() ​

Pads the end of the string with a filler string to reach a target length.

SignaturepadEnd(targetLength: i64, fill?: string): string
tyrus
const label: string = "Name";
const padded: string = label.padEnd(20, "."); // "Name................"

error

tyrus
const label: string = "Name";
const padded: string = label.padEnd("20"); 
text
error[E0308]: type mismatch for `padEnd`: expected `usize`, found `string`
at /src/main.tyr:2:24
const padded: string = label.padEnd("20");
                       ^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

concat() ​

Concatenates the string with one or more strings.

Keeping a string beyond the value it was read from, pushing it into an array, capturing it in a closure, storing it in a field, no longer copies the text. The two share one buffer and each holds a reference to it, which is sound precisely because a string is immutable: two readers of one buffer can never disagree.

A chain of + costs one allocation, not one per operator: a + b + c + d measures every operand first, each string carries its own length, so measuring reads nothing, and then fills a single buffer.

Signatureconcat(...strings: string[]): string
tyrus
const first: string = "Hello";
const second: string = " World";
const combined: string = first.concat(second); // "Hello World"

error

tyrus
const first: string = "Hello";
const combined: string = first.concat(42); 
text
error[E0308]: type mismatch for `concat`: expected `string`, found `integer literal`
at /src/main.tyr:2:26
const combined: string = first.concat(42);
                         ^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

split() ​

Splits the string into an array of substrings using a separator.

Signaturesplit(separator: string | Regex): string[]
tyrus
const csv: string = "rust,go,tyrus";
const languages: string[] = csv.split(",");
// ["rust", "go", "tyrus"]

const sentence: string = "hello world";
const words: string[] = sentence.split(" ");
// ["hello", "world"]

error

tyrus
const csv: string = "rust,go,tyrus";
const languages: string[] = csv.split(42); 
text
error[E0308]: type mismatch for `split`: expected `string`, found `integer literal`
at /src/main.tyr:2:29
const languages: string[] = csv.split(42);
                            ^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

HTML and encoding ​


stripHtml() ​

Removes all HTML tags from the string, leaving only the text content. Decodes common HTML entities (&lt;, &gt;, &amp;, &quot;, &#39;).

SignaturestripHtml(): string
tyrus
const html: string = "<p>Hello <b>World</b></p>";
const text: string = html.stripHtml(); // Hello World

const link: string = "<a href=\"url\">click here</a>";
const plain: string = link.stripHtml(); // click here

error

tyrus
const flag: boolean = true;
const text: string = flag.stripHtml(); 
text
error[E0599]: no method named `stripHtml` for type `boolean`
at /src/main.tyr:2:22
const text: string = flag.stripHtml();
                     ^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

escapeHtml() ​

Escapes special characters into HTML entities (& < > " '), preventing XSS injection.

SignatureescapeHtml(): string
tyrus
const code: string = "<script>alert('hack')</script>";
const safe: string = code.escapeHtml(); // "&lt;script&gt;alert(&#39;hack&#39;)&lt;/script&gt;"

error

tyrus
const flag: boolean = true;
const safe: string = flag.escapeHtml(); 
text
error[E0599]: no method named `escapeHtml` for type `boolean`
at /src/main.tyr:2:22
const safe: string = flag.escapeHtml();
                     ^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

urlEncode() ​

Percent-encodes the string for use as a URL query parameter. Encodes all characters except unreserved characters (letters, digits, -, _, ., ~).

SignatureurlEncode(): string
tyrus
const query: string = "hello world & friends";
const encoded: string = query.urlEncode(); // "hello%20world%20%26%20friends"

const path: string = "a/b?c=d";
const safe: string = path.urlEncode(); // "a%2Fb%3Fc%3Dd"

error

tyrus
const flag: boolean = true;
const encoded: string = flag.urlEncode(); 
text
error[E0599]: no method named `urlEncode` for type `boolean`
at /src/main.tyr:2:25
const encoded: string = flag.urlEncode();
                        ^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

urlDecode() ​

Decodes a percent-encoded string back to its original form.

SignatureurlDecode(): string
tyrus
const encoded: string = "hello%20world";
const decoded: string = encoded.urlDecode(); // "hello world"

const special: string = "TitenQ%20%26%20friends";
const result: string = special.urlDecode(); // "TitenQ & friends"

error

tyrus
const flag: boolean = true;
const decoded: string = flag.urlDecode(); 
text
error[E0599]: no method named `urlDecode` for type `boolean`
at /src/main.tyr:2:25
const decoded: string = flag.urlDecode();
                        ^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

Pattern matching ​


match() ​

Matches the string against a regular expression and returns captured groups.

Signaturematch(pattern: Regex): string[]?
tyrus
const text: string = "order-123";
const result: string[]? = text.match(/^order-(\d+)$/);
if (result) {
    const orderId: string = result[0]; // "order-123"
    const digits: string = result[1]; // "123"
}

error

tyrus
const text: string = "order-123";
const result: string[]? = text.match("order"); 
text
error[E0308]: type mismatch for `match`: expected `Regex`, found `string`
at /src/main.tyr:2:27
const result: string[]? = text.match("order");
                          ^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

matchAll() ​

Finds all matches of a regular expression in the string.

SignaturematchAll(pattern: Regex): string[][]?
tyrus
const text: string = "a1 b2 c3";
const matches: string[][]? = text.matchAll(/[a-z]\d/g);
if (matches) {
    for (const match of matches) {
        print(match[0]); // "a1", "b2", "c3"
    }
}

error

tyrus
const text: string = "a1 b2 c3";
const matches: string[][]? = text.matchAll("[a-z]"); 
text
error[E0308]: type mismatch for `matchAll`: expected `Regex`, found `string`
at /src/main.tyr:2:30
const matches: string[][]? = text.matchAll("[a-z]");
                             ^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`

Iteration ​


chars() ​

Iterates over the characters of the string.

Signaturechars(): char[]
tyrus
const emoji: string = "hello";
for (const letter of emoji.chars()) {
    print(letter); // "h", "e", "l", "l", "o"
}

error

tyrus
const value: i32 = 42;
for (const letter of value.chars()) { 
}
text
error[E0599]: no method named `chars` for type `i32`
at /src/main.tyr:2:22
for (const letter of value.chars()) {
                     ^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type

graphemes() ​

Iterates over the string's grapheme clusters, the characters a reader perceives, where one cluster may hold several scalar values.

Signaturegraphemes(): string[]
tyrus
const astronaut: string = "a👨‍🚀é";

for (const cluster of astronaut.graphemes()) {
    print(cluster); // "a", "👨‍🚀", "é"
}

print(astronaut.chars().length);      // 5, scalar values
print(astronaut.graphemes().length);  // 3, clusters

Working with Numbers ​

parseInt ​

Parses a string and returns an optional integer. Returns empty when the input is not a valid integer representation.

SignatureparseInt(value: string): i64?
tyrus
const count: i64? = parseInt("42 items"); // 42
const port: i32? = parseInt("8080"); // 8080
const overflow: i64? = parseInt("9999999999"); // value
const negative: u32? = parseInt("-5"); // empty

parseFloat ​

Parses a string and returns an optional floating-point number. Returns empty when the input is not a valid float representation.

SignatureparseFloat(value: string): f64?
tyrus
const ratio: f64? = parseFloat("3.14"); // 3.14
const scientific: f64? = parseFloat("1.5e3"); // 1500.0
const invalid: f64? = parseFloat("abc"); // empty

toString ​

Converts a value to its string representation.

SignaturetoString(): string
tyrus
const number: i32 = 42;
const text: string = number.toString(); // "42"

const flag: boolean = true;
const label: string = flag.toString(); // "true"

Regex Integration ​

Strings work natively with the Regex type:

tyrus
const text: string = "error: file not found";
const hasError: boolean = text.includes("error"); // true
const firstSpace: i64 = text.indexOf(" "); // 5
const afterColon: string = text.substring(firstSpace + 1);
// "file not found"

const matched: string[]? = text.match(/error: (.+)/);

if (matched) {
    const message: string = matched[1]; // "file not found"
}

const replaced: string = text.replace("error", "warning");
// "warning: file not found"

const parts: string[] = text.split(" ");
// ["error:", "file", "not", "found"]

String literals are not char A multi-character string literal cannot be assigned to char:

error

tyrus
const letter: char = "ab"; 

error

text
error[E0708]: a `char` holds exactly one character, but `ab` has 2
at /src/main.tyr:1:22
const letter: char = "ab";
                     ^^^^
help: annotate the value with `string` to hold text of any length, or keep a single character