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
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.
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.
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: 0042Una 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.
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.
const astronaut: string = "👨🚀";
print(astronaut.chars().length); // 3
print(astronaut.graphemes().length); // 1Indexació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
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 characterlength 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ía | Métodos |
|---|---|
| Conversión de mayúsculas/minúsculas | toUpperCase(), toLowerCase() |
| Transformación de caso | toSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase() |
| Eliminación de espacios | trim(), trimStart(), trimEnd() |
| Búsqueda | includes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search() |
| Rebanado y extracción | slice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis() |
| Transformación | replace(), repeat(), padStart(), padEnd(), concat(), split() |
| HTML y codificación | stripHtml(), escapeHtml(), urlEncode(), urlDecode() |
| Coincidencia de patrones | match(), matchAll() |
| Iteración | chars(), graphemes() |
Conversión de mayúsculas/minúsculas
toUpperCase()
Devuelve la cadena con todos los caracteres en mayúscula.
toUpperCase(): stringconst shout: string = "tyrus";
const loud: string = shout.toUpperCase(); // TYRUSerror
const flag: boolean = true;
const upper: string = flag.toUpperCase(); 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 typetoLowerCase()
Devuelve la cadena con todos los caracteres en minúscula.
toLowerCase(): stringconst shout: string = "TYRUS";
const quiet: string = shout.toLowerCase(); // "tyrus"error
const flag: boolean = true;
const lower: string = flag.toLowerCase(); 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 typeTransformació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.
toSlugCase(): stringconst 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
const flag: boolean = true;
const slug: string = flag.toSlugCase(); 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 typetoDashCase()
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.
toDashCase(): stringconst 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
const flag: boolean = true;
const dashed: string = flag.toDashCase(); 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 typetoKebabCase()
Alias de toDashCase().
toKebabCase(): stringconst 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.
toPascalCase(): stringconst phrase: string = "hello world example";
const pascal: string = phrase.toPascalCase(); // "HelloWorldExample"
const snake: string = "hello_world_example";
const result: string = snake.toPascalCase(); // "HelloWorldExample"error
const flag: boolean = true;
const pascal: string = flag.toPascalCase(); 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 typetoCamelCase()
Convierte la cadena a camelCase. La primera palabra está en minúscula, las siguientes se capitalizan.
toCamelCase(): stringconst phrase: string = "hello world example";
const camel: string = phrase.toCamelCase(); // "helloWorldExample"
const pascal: string = "HelloWorldExample";
const result: string = pascal.toCamelCase(); // "helloWorldExample"error
const flag: boolean = true;
const camel: string = flag.toCamelCase(); 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 typetoSnakeCase()
Convierte la cadena a snake_case (palabras en minúscula unidas por guiones bajos).
toSnakeCase(): stringconst 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
const flag: boolean = true;
const snake: string = flag.toSnakeCase(); 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 typeEliminación de espacios
trim()
Elimina espacios en blanco de ambos extremos de la cadena.
trim(): stringconst padded: string = " hello ";
const clean: string = padded.trim(); // "hello"error
const value: i32 = 42;
const clean: string = value.trim(); 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 typetrimStart()
Elimina espacios en blanco del inicio de la cadena.
trimStart(): stringconst padded: string = " hello ";
const left: string = padded.trimStart(); // "hello "error
const value: i32 = 42;
const left: string = value.trimStart(); 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 typetrimEnd()
Elimina espacios en blanco del final de la cadena.
trimEnd(): stringconst padded: string = " hello ";
const right: string = padded.trimEnd(); // " hello"error
const value: i32 = 42;
const right: string = value.trimEnd(); 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 typeBúsqueda
includes()
Comprueba si la cadena contiene una subcadena.
includes(search: string): booleanconst sentence: string = "tyrus is native";
const found: boolean = sentence.includes("native"); // trueerror
const sentence: string = "tyrus is native";
const found: boolean = sentence.includes(42); 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.
startsWith(search: string): booleanconst filename: string = "main.tyr";
const isSource: boolean = filename.startsWith("main."); // trueerror
const filename: string = "main.tyr";
const isSource: boolean = filename.startsWith(true); 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.
endsWith(search: string): booleanconst filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(".tyr"); // trueerror
const filename: string = "main.tyr";
const isTyrus: boolean = filename.endsWith(42); 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.
indexOf(search: string, start?: i64): i64const text: string = "hello world";
const position: i64 = text.indexOf("world"); // 6
const missing: i64 = text.indexOf("rust"); // -1error
const text: string = "hello world";
const position: i64 = text.indexOf(["hello"]); 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.
lastIndexOf(search: string, start?: i64): i64const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf("/"); // 3error
const path: string = "src/main.tyr";
const lastSlash: i64 = path.lastIndexOf(42); 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>`search()
Busca un patrón usando una expresión regular y devuelve el índice de la coincidencia.
search(pattern: Regex): i64const main = (): void => {
const email: string = "[email protected]";
const atSign: i32 = email.search(/@/); // 4
print(atSign); // 4
};error
const main = (): void => {
const email: string = "[email protected]";
const atSign: i32 = email.search("@");
};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.
slice(start?: i64, end?: i64): stringconst code: string = "tyrus-lang";
const lang: string = code.slice(6); // "lang"
const sub: string = code.slice(0, 5); // "tyrus"error
const code: string = "tyrus-lang";
const result: string = code.slice("6"); 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.
substring(start: i64, end?: i64): stringconst version: string = "v0.1.0";
const numeric: string = version.substring(1); // "0.1.0"error
const version: string = "v0.1.0";
const numeric: string = version.substring("1"); 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.
charAt(index: i64): stringconst word: string = "tyrus";
const letter: string = word.charAt(0); // "t"error
const word: string = "tyrus";
const letter: string = word.charAt("0"); 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.
charCodeAt(index: i64): u32const main = (): void => {
const letter: string = "A";
const code: i32 = letter.charCodeAt(0); // 65
print(code); // 65
};error
const main = (): void => {
const letter: string = "A";
const code: i32 = letter.charCodeAt("0");
};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.
truncate(maxLength: i64): stringconst text: string = "Hello, World!";
const short: string = text.truncate(5); // "Hello"
const small: string = text.truncate(3); // "Hel"error
const text: string = "hello";
const bad: string = text.truncate("ten"); 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.
truncateEllipsis(maxLength: i64): stringconst text: string = "Hello, World!";
const short: string = text.truncateEllipsis(8); // "Hello..."
const fits: string = "hello".truncateEllipsis(10); // "hello"error
const text: string = "hello";
const bad: string = text.truncateEllipsis("ten"); 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.
replace(search: string | Regex, replacement: string): stringconst path: string = "src/main.ts";
const updated: string = path.replace(".ts", ".tyr"); // "src/main.tyr"error
const path: string = "src/main.ts";
const updated: string = path.replace(".ts", 42); 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.
repeat(count: i64): stringconst divider: string = "-".repeat(20); // "--------------------"
const pattern: string = "ab".repeat(3); // "ababab"error
const divider: string = "-".repeat("20"); 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.
padStart(targetLength: i64, fill?: string): stringconst id: string = "42";
const padded: string = id.padStart(5, "0"); // "00042"error
const id: string = "42";
const padded: string = id.padStart("5"); 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.
padEnd(targetLength: i64, fill?: string): stringconst label: string = "Name";
const padded: string = label.padEnd(20, "."); // "Name................"error
const label: string = "Name";
const padded: string = label.padEnd("20"); 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.
concat(...strings: string[]): stringconst first: string = "Hello";
const second: string = " World";
const combined: string = first.concat(second); // "Hello World"error
const first: string = "Hello";
const combined: string = first.concat(42); 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.
split(separator: string | Regex): string[]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
const csv: string = "rust,go,tyrus";
const languages: string[] = csv.split(42); 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 (<, >, &, ", ').
stripHtml(): stringconst 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 hereerror
const flag: boolean = true;
const text: string = flag.stripHtml(); 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 typeescapeHtml()
Escapa caracteres especiales a entidades HTML (& < > " '), previniendo inyección XSS.
escapeHtml(): stringconst code: string = "<script>alert('hack')</script>";
const safe: string = code.escapeHtml(); // "<script>alert('hack')</script>"error
const flag: boolean = true;
const safe: string = flag.escapeHtml(); 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 typeurlEncode()
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, -, _, ., ~).
urlEncode(): stringconst 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
const flag: boolean = true;
const encoded: string = flag.urlEncode(); 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 typeurlDecode()
Decodifica una cadena codificada con percent-encoding de vuelta a su forma original.
urlDecode(): stringconst 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
const flag: boolean = true;
const decoded: string = flag.urlDecode(); 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 typeCoincidencia de patrones
match()
Compara la cadena con una expresión regular y devuelve grupos capturados.
match(pattern: Regex): string[]?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
const text: string = "order-123";
const result: string[]? = text.match("order"); 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.
matchAll(pattern: Regex): string[][]?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
const text: string = "a1 b2 c3";
const matches: string[][]? = text.matchAll("[a-z]"); 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.
chars(): char[]const emoji: string = "hello";
for (const letter of emoji.chars()) {
print(letter); // "h", "e", "l", "l", "o"
}error
const value: i32 = 42;
for (const letter of value.chars()) {
}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 typegraphemes()
Itera sobre los grupos de grafemas de la cadena, los caracteres que un lector percibe, donde un grupo puede contener varios valores escalares.
graphemes(): string[]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, clustersTrabajando 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.
parseInt(value: string): i64?const count: i64? = parseInt("42 items"); // 42
const port: i32? = parseInt("8080"); // 8080
const overflow: i64? = parseInt("9999999999"); // value
const negative: u32? = parseInt("-5"); // emptyparseFloat
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.
parseFloat(value: string): f64?const ratio: f64? = parseFloat("3.14"); // 3.14
const scientific: f64? = parseFloat("1.5e3"); // 1500.0
const invalid: f64? = parseFloat("abc"); // emptytoString
Convierte un valor a su representación de cadena.
toString(): stringconst 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:
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
const letter: char = "ab"; error
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