Skip to content

Strings ​

string é o tipo nativo de texto UTF-8 no tyrus. A sintaxe fonte é concisa, enquanto a implementação de runtime é nativa.

Strings com aspas ​

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

O formatter normaliza aspas conforme quote_style, exceto quando configurado como "off", que preserva as aspas e escapes originais de cada literal de string.

Strings multilinha ​

Uma string delimitada por """ pode ocupar várias linhas mantendo o alinhamento com o código ao redor. O compilador remove o recuo em tempo de compilação: de cada linha, ele retira tantos espaços à esquerda quanto o """ de fechamento estiver recuado, e descarta uma primeira linha deixada em branco logo após o """ de abertura. O resultado é um literal string comum, então não há custo em runtime para escrever uma query ou um template alinhado em vez de rente à margem esquerda.

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

A margem de dedent conta apenas espaços; um """ fechado numa linha recuada com tabs mede margem zero, então use espaços para o recuo que você quer remover.

Template literals ​

Use template literals para interpolação e texto multiline.

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

Uma interpolação pode carregar um especificador de formato depois de :, .Nf fixa um float em exatamente N casas decimais, e 0Nd preenche um inteiro com zeros à esquerda até uma largura total de N caracteres. .Nf exige um valor float e 0Nd exige um valor inteiro; uma incompatibilidade é um erro de compilação (E0717) que nomeia o tipo exigido.

Um valor de tipo união também pode ser interpolado. Qual variante ele guarda é um fato de tempo de execução, então a renderização é escolhida em tempo de execução e coincide com o que o print imprimiria para aquela variante.

Tipos string literais ​

String literals podem participar de unions literais e tagged unions.

Uma união de literais é um valor comum: compare-a com qualquer uma de suas variantes (status === "active"), ramifique com um match que não precisa de _ quando cobre toda variante, construa uma com um ternário, junte várias num array e chame nela qualquer coisa que uma string aceite, toda variante de uma união de literais de string é uma string. A comparação é uma checagem de um byte em vez de comparação de texto, porque uma união dessas é representada por qual variante ela guarda e nada mais.

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

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

Valores literais não são membros de enum

Use strings literais para pequenos domínios textuais fechados. Use enum quando o domínio precisa de membros nomeados e semântica nativa de enum.

Grupos de grafemas ​

O chars() devolve valores escalares Unicode; o graphemes() devolve o que um leitor chama de caracteres. Os dois diferem sempre que um caractere visível é escrito com vários valores escalares, um emoji montado com sequência de zero-width joiner, ou uma letra seguida de acento combinante.

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

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

Indexação, fatiamento e length contam valores escalares, não grupos: essa é a unidade em que toda posição da API de string é medida, e é o que faz text.charAt(text.length - 1) ser o último. O graphemes() responde à pergunta de exibição, quantos caracteres um leitor vê, e onde um cursor pararia, e devolve string[], porque um grupo pode conter mais de um valor escalar.

Propriedades de string ​

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 é lido do valor, não contado: uma string carrega a contagem de caracteres junto com o texto, então perguntá-la custa o mesmo com três caracteres ou com três milhões. U+0000 é um caractere comum numa string, o texto é delimitado pelo comprimento registrado, não por um terminador, então "a\u{0}b".length é 3 e ele sobrevive inteiro a comparação, interpolação e impressão.

length conta caracteres, valores escalares Unicode, nunca os bytes UTF-8 subjacentes, então concorda com chars() em qualquer texto. Toda posição na API de string usa essa mesma unidade: charAt(), charCodeAt(), slice(), substring(), indexOf(), lastIndexOf(), padStart() e padEnd() contam caracteres, o que é o que faz text.charAt(text.length - 1) ser o último caractere de qualquer string, acentuada ou não.

Métodos ​

CategoriaMétodos
Conversão de caixatoUpperCase(), toLowerCase()
Transformação de caixatoSlugCase(), toDashCase(), toKebabCase(), toPascalCase(), toCamelCase(), toSnakeCase()
Remoção de espaçostrim(), trimStart(), trimEnd()
Buscaincludes(), startsWith(), endsWith(), indexOf(), lastIndexOf(), search()
Fatias e extraçãoslice(), substring(), charAt(), charCodeAt(), truncate(), truncateEllipsis()
Transformaçãoreplace(), repeat(), padStart(), padEnd(), concat(), split()
HTML e codificaçãostripHtml(), escapeHtml(), urlEncode(), urlDecode()
Correspondência de padrãomatch(), matchAll()
Iteraçãochars(), graphemes()

Conversão de caixa ​


toUpperCase() ​

Retorna a string com todos os caracteres em maiúsculo.

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

Retorna a string com todos os caracteres em minúsculo.

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

Transformação de caixa ​


toSlugCase() ​

Normaliza a string para um slug amigável a URLs. Remove acentos via decomposição NFKD, remove caracteres não alfanuméricos e junta palavras com hífens.

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

Converte a string para dash-case (palavras minúsculas unidas por hífens). Tokeniza por espaços, underscores, hífens e limites de camelCase. Diferente de toSlugCase(), acentos são preservados.

AssinaturatoDashCase(): 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().

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

toKebabCase() is an alias for toDashCase().


toPascalCase() ​

Converte a string para PascalCase. Cada palavra é capitalizada e unida sem separadores.

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

Converte a string para camelCase. A primeira palavra é minúscula, as demais são capitalizadas.

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

Converte a string para snake_case (palavras minúsculas unidas por underscores).

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

Remoção de espaços ​


trim() ​

Remove espaços em branco de ambas as extremidades da string.

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

Remove espaços em branco do início da string.

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

Remove espaços em branco do final da string.

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

Busca ​


includes() ​

Verifica se a string contém uma substring.

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

Verifica se a string começa com uma substring.

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

Verifica se a string termina com uma substring.

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

Retorna o índice da primeira ocorrência de uma substring, ou -1.

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

Retorna o índice da última ocorrência de uma substring, ou -1.

AssinaturalastIndexOf(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 um padrão usando expressão regular e retorna o índice da correspondência.

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

Fatias e extração ​


slice() ​

Extrai uma seção da string e a retorna como uma nova string.

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

Retorna uma substring a partir de um índice dado.

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

Retorna o caractere em um índice especificado.

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

Retorna o código Unicode do caractere em um índice especificado.

AssinaturacharCodeAt(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 a string para um número máximo de code points.

Assinaturatruncate(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 a string para um número máximo de code points e anexa ... quando o texto excede o limite.

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

Transformação ​


replace() ​

Substitui uma substring ou padrão por uma string de substituição.

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

Retorna uma nova string com o original repetido um número dado de vezes.

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

Preenche o início da string com um caractere de preenchimento até atingir um comprimento alvo.

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

Preenche o final da string com um caractere de preenchimento até atingir um comprimento alvo.

AssinaturapadEnd(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 a string com uma ou mais strings.

Guardar uma string além do valor de onde ela veio, colocá-la num array, capturá-la numa closure, armazená-la num campo, não copia mais o texto. As duas compartilham um buffer e cada uma segura uma referência a ele, o que é seguro justamente porque uma string é imutável: dois leitores de um buffer não têm como discordar.

Uma cadeia de + custa uma alocação, não uma por operador: a + b + c + d mede todos os operandos primeiro, cada string carrega o próprio comprimento, então medir não lê nada, e só então preenche um único buffer.

Assinaturaconcat(...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 a string em um array de substrings usando um separador.

Assinaturasplit(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 e codificação ​


stripHtml() ​

Remove todas as tags HTML da string, deixando apenas o conteúdo textual. Decodifica entidades HTML comuns (&lt;, &gt;, &amp;, &quot;, &#39;).

AssinaturastripHtml(): 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 especiais para entidades HTML (& < > " '), prevenindo injeção XSS.

AssinaturaescapeHtml(): 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 a string com percent-encoding para uso como parâmetro de query URL. Codifica todos os caracteres exceto caracteres não reservados (letras, dígitos, -, _, ., ~).

AssinaturaurlEncode(): 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 uma string codificada com percent-encoding de volta à sua forma original.

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

Correspondência de padrão ​


match() ​

Compara a string com uma expressão regular e retorna grupos capturados.

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

Encontra todas as correspondências de uma expressão regular na string.

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

Iteração ​


chars() ​

Itera sobre os caracteres da string.

Assinaturachars(): 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 os grupos de grafemas da string, os caracteres que um leitor percebe, onde um grupo pode conter vários valores escalares.

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

Trabalhando com números ​

parseInt ​

Analisa uma string e retorna um inteiro opcional. Retorna vazio quando a entrada não é uma representação válida de inteiro.

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

Analisa uma string e retorna um número de ponto flutuante opcional. Retorna vazio quando a entrada não é uma representação válida de float.

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

Converte um valor para sua representação em string.

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

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

Integração com Regex ​

Strings trabalham nativamente com o 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"]

Literais de string não são char Um literal de string com múltiplos caracteres não pode ser atribuído 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