Skip to content

Cadenas de texto ​

string es el tipo nativo de texto UTF-8 en tyrus. La sintaxis fuente es concisa, mientras que la implementación de runtime es nativa.

Cadenas con comillas ​

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

El formateador normaliza las comillas según quote_style, salvo cuando se configura como "off", que preserva las comillas y escapes originales de cada literal de cadena.

Cadenas multilínea ​

Una cadena delimitada por """ puede ocupar varias líneas manteniendo la alineación con el código circundante. El compilador la desindenta en tiempo de compilación: de cada línea, quita tantos espacios a la izquierda como los que tenga el """ de cierre, y descarta una primera línea dejada en blanco justo después del """ de apertura. El resultado es un literal string común, así que no hay costo en runtime por escribir una consulta o una plantilla alineada en lugar de una pegada al margen izquierdo.

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

El margen de desindentación solo cuenta espacios; un """ cerrado en una línea indentada con tabulaciones mide un margen de cero, así que usa espacios para la indentación que quieras eliminar.

Template literals ​

Usa template literals para interpolación y texto multilínea.

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

Una interpolación puede llevar un especificador de formato después de :, .Nf fija un float en exactamente N decimales, y 0Nd rellena un entero con ceros a la izquierda hasta un ancho total de N caracteres. .Nf exige un valor float y 0Nd exige un valor entero; un desajuste es un error de compilación (E0717) que nombra el tipo requerido.

Un valor de tipo unión también puede interpolarse. Qué variante contiene es un hecho de tiempo de ejecución, así que la renderización se elige en tiempo de ejecución y coincide con lo que print imprimiría para esa variante.

Tipos de cadena literales ​

Los literales de cadena pueden participar en uniones literales y uniones etiquetadas.

Una unión de literales es un valor común: compárala con cualquiera de sus variantes (status === "active"), ramifica con un match que no necesita _ cuando cubre toda variante, construye una con un ternario, júntalas en un array y llama en ella cualquier cosa que una string acepte, toda variante de una unión de literales de string es una string. La comparación es un chequeo de un byte en vez de comparación de texto, porque una unión así se representa por qué variante contiene y nada más.

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

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

Los valores literales no son miembros de enum

Usa literales de cadena para dominios textuales cerrados pequeños. Usa enum cuando el dominio necesita miembros nombrados y semántica nativa de enum.

Grupos de grafemas ​

chars() devuelve valores escalares Unicode; graphemes() devuelve lo que un lector llama caracteres. Los dos difieren siempre que un carácter visible se escribe con varios valores escalares, un emoji armado con secuencia de zero-width joiner, o una letra seguida de acento combinante.

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

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

Indexación, corte y length cuentan valores escalares, no grupos: esa es la unidad en la que se mide toda posición de la API de cadenas, y es lo que hace que text.charAt(text.length - 1) sea el último. graphemes() responde a la pregunta de visualización, cuántos caracteres ve un lector, y dónde se detendría un cursor, y devuelve string[], porque un grupo puede contener más de un valor escalar.

Propiedades de cadena ​

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 se lee del valor, no se cuenta: una string lleva su recuento de caracteres junto al texto, así que preguntarlo cuesta lo mismo con tres caracteres que con tres millones. U+0000 es un carácter corriente en una string, el texto lo delimita la longitud registrada, no un terminador, así que "a\u{0}b".length es 3 y sobrevive entero a la comparación, la interpolación y la impresión.

length cuenta caracteres, valores escalares Unicode, nunca los bytes UTF-8 subyacentes, por lo que coincide con chars() en cualquier texto. Toda posición de la API de cadenas usa esa misma unidad: charAt(), charCodeAt(), slice(), substring(), indexOf(), lastIndexOf(), padStart() y padEnd() cuentan caracteres, que es lo que hace que text.charAt(text.length - 1) sea el último carácter de cualquier cadena, acentuada o no.

Métodos de cadena ​

CategoríaMétodos
Conversión de mayúsculas/minúsculastoUpperCase(), toLowerCase()
Transformación de casotoSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase()
Eliminación de espaciostrim(), trimStart(), trimEnd()
Búsquedaincludes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search()
Rebanado y extracciónslice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis()
Transformaciónreplace(), repeat(), padStart(), padEnd(), concat(), split()
HTML y codificaciónstripHtml(), escapeHtml(), urlEncode(), urlDecode()
Coincidencia de patronesmatch(), matchAll()
Iteraciónchars(), graphemes()

Conversión de mayúsculas/minúsculas ​


toUpperCase() ​

Devuelve la cadena con todos los caracteres en mayúscula.

FirmatoUpperCase(): 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() ​

Devuelve la cadena con todos los caracteres en minúscula.

FirmatoLowerCase(): 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

Transformación de caso ​


toSlugCase() ​

Normaliza la cadena en un slug amigable para URLs. Elimina acentos mediante descomposición NFKD, elimina caracteres no alfanuméricos y une palabras con guiones.

FirmatoSlugCase(): 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() ​

Convierte la cadena a dash-case (palabras en minúscula unidas por guiones). Tokeniza por espacios, guiones bajos, guiones y límites de camelCase. A diferencia de toSlugCase(), los acentos se preservan.

FirmatoDashCase(): 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 de toDashCase().

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

toKebabCase() is an alias for toDashCase().


toPascalCase() ​

Convierte la cadena a PascalCase. Cada palabra se capitaliza y se une sin separadores.

FirmatoPascalCase(): 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() ​

Convierte la cadena a camelCase. La primera palabra está en minúscula, las siguientes se capitalizan.

FirmatoCamelCase(): 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() ​

Convierte la cadena a snake_case (palabras en minúscula unidas por guiones bajos).

FirmatoSnakeCase(): 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

Eliminación de espacios ​


trim() ​

Elimina espacios en blanco de ambos extremos de la cadena.

Firmatrim(): 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() ​

Elimina espacios en blanco del inicio de la cadena.

FirmatrimStart(): 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() ​

Elimina espacios en blanco del final de la cadena.

FirmatrimEnd(): 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

Búsqueda ​


includes() ​

Comprueba si la cadena contiene una subcadena.

Firmaincludes(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() ​

Comprueba si la cadena comienza con una subcadena.

FirmastartsWith(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() ​

Comprueba si la cadena termina con una subcadena.

FirmaendsWith(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() ​

Devuelve el índice de la primera aparición de una subcadena, o -1.

FirmaindexOf(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() ​

Devuelve el índice de la última aparición de una subcadena, o -1.

FirmalastIndexOf(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>`

Busca un patrón usando una expresión regular y devuelve el índice de la coincidencia.

Firmasearch(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>`

Rebanado y extracción ​


slice() ​

Extrae una sección de la cadena y la devuelve como una nueva cadena.

Firmaslice(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() ​

Devuelve una subcadena a partir de un índice dado.

Firmasubstring(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() ​

Devuelve el carácter en un índice especificado.

FirmacharAt(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() ​

Devuelve el código Unicode del carácter en un índice especificado.

FirmacharCodeAt(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() ​

Trunca la cadena a un número máximo de code points.

Firmatruncate(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() ​

Trunca la cadena a un número máximo de code points y agrega ... cuando el texto excede el límite.

FirmatruncateEllipsis(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>`

Transformación ​


replace() ​

Reemplaza una subcadena o patrón con una cadena de reemplazo.

Firmareplace(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() ​

Devuelve una nueva cadena con la original repetida un número dado de veces.

Firmarepeat(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() ​

Rellena el inicio de la cadena con un carácter de relleno hasta alcanzar una longitud objetivo.

FirmapadStart(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() ​

Rellena el final de la cadena con un carácter de relleno hasta alcanzar una longitud objetivo.

FirmapadEnd(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() ​

Concatena la cadena con una o más cadenas.

Conservar una string más allá del valor del que se leyó, meterla en un arreglo, capturarla en un cierre, guardarla en un campo, ya no copia el texto. Ambas comparten un búfer y cada una mantiene una referencia a él, lo cual es seguro precisamente porque una string es inmutable: dos lectores de un búfer no pueden discrepar.

Una cadena de + cuesta una asignación, no una por operador: a + b + c + d mide todos los operandos primero, cada string lleva su propia longitud, así que medir no lee nada, y solo entonces llena un único búfer.

Firmaconcat(...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() ​

Divide la cadena en un array de subcadenas usando un separador.

Firmasplit(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 y codificación ​


stripHtml() ​

Elimina todas las etiquetas HTML de la cadena, dejando solo el contenido textual. Decodifica entidades HTML comunes (&lt;, &gt;, &amp;, &quot;, &#39;).

FirmastripHtml(): 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() ​

Escapa caracteres especiales a entidades HTML (& < > " '), previniendo inyección XSS.

FirmaescapeHtml(): 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() ​

Codifica la cadena con percent-encoding para uso como parámetro de query URL. Codifica todos los caracteres excepto los no reservados (letras, dígitos, -, _, ., ~).

FirmaurlEncode(): 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() ​

Decodifica una cadena codificada con percent-encoding de vuelta a su forma original.

FirmaurlDecode(): 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

Coincidencia de patrones ​


match() ​

Compara la cadena con una expresión regular y devuelve grupos capturados.

Firmamatch(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() ​

Encuentra todas las coincidencias de una expresión regular en la cadena.

FirmamatchAll(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>`

Iteración ​


chars() ​

Itera sobre los caracteres de la cadena.

Firmachars(): 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() ​

Itera sobre los grupos de grafemas de la cadena, los caracteres que un lector percibe, donde un grupo puede contener varios valores escalares.

Firmagraphemes(): 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

Trabajando con números ​

parseInt ​

Analiza una cadena y devuelve un entero opcional. Devuelve vacío cuando la entrada no es una representación válida de entero.

FirmaparseInt(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 ​

Analiza una cadena y devuelve un número de punto flotante opcional. Devuelve vacío cuando la entrada no es una representación válida de flotante.

FirmaparseFloat(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 ​

Convierte un valor a su representación de cadena.

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

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

Integración con Regex ​

Las cadenas funcionan de forma nativa con el tipo Regex:

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"]

Los literales de cadena no son char Un literal de cadena de múltiples caracteres no puede asignarse a 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