KScript documentação
PT

Idioma

Traduzido automaticamente do inglês, que é a versão original.

campos e métodos de string

Texto. Uma string que contém um número também pode usar métodos de número.

Texto é um string: qualquer coisa entre aspas. 'Single quotes' mantêm exatamente o que você escreve, e "double quotes" preenchem com o que está em { }, então "Hello { $name }" lê a variável. Para texto em várias linhas, escreva um bloco de texto entre linhas ```, que mantém todas as quebras de linha como escritas.

Os métodos de texto nunca alteram o texto sobre o qual são chamados; cada um devolve um novo texto (ou um número, uma lista ou um bool), então encadeie-os ou guarde o resultado em uma variável:

<let name="name" value="'  ada LOVELACE '" />
<let name="tidy" value="$name->trim()->title()" />
<echo value="$tidy" /> <!-- 'Ada Lovelace' because the spaces go and each word gets a capital -->
<echo value="$name" /> <!-- '  ada LOVELACE ' because the text itself is unchanged -->
$name = '  ada LOVELACE '
$tidy = $name->trim()->title()
echo $tidy   // 'Ada Lovelace' because the spaces go and each word gets a capital
echo $name   // '  ada LOVELACE ' because the text itself is unchanged

As posições começam em 0, e uma posição negativa conta a partir do fim. Um caractere como um emoji conta como duas posições, e nenhum método o divide ao meio. As comparações diferenciam maiúsculas e minúsculas, a menos que você passe a flag ignore_case.

Descubra sobre o texto: count · count_of · is_empty · is_blank · is_numeric · contains · starts_with · ends_with · index_of · matches

Extraia uma parte dele: first · last · slice · before · after · truncate · find_all

Limpe e altere-o: trim · squish · strip · replace · upper · lower · capitalize · title · case · pad · repeat · reverse · wrap · mask · normalize_unicode

Divida em uma lista: split · lines · blocks · words · chars · numbers · grid · shapes

Leia como outro valor: to_number · to_int · to_bool · to_date, ou outro formato com ->convert()

Torne seguro para enviar: escape · url_encode · url_decode · to_base64 · from_base64 · md5 · sha1 · sha256 · sha512 · hmac

Um campo é um dado simples sobre o valor, lido com um ponto e sem colchetes: $value.name. Um método recebe argumentos ou executa alguma ação, e é chamado com ->: $value->name(arguments), ou com o valor passado por pipe: $value |> name(arguments).

Do KScript.Core

#string->after(text: string, last?: bool) → string

O texto depois da primeira vez que o texto aparece (ou da última vez, com last), ou o texto inteiro quando ele não aparece: 'a.tar.gz'->after('.', last) é gz.

->after(text, last?) retorna o texto depois da primeira vez que text aparece, ou depois da última vez com last. Quando text não está presente, você recebe o texto inteiro de volta:

<let name="file" value="'archive.tar.gz'" />
<echo value="$file->after('.')" /> <!-- 'tar.gz' because it cuts at the first dot -->
<echo value="$file->after('.', last)" /> <!-- 'gz' because it cuts at the last dot -->
<echo value="'no-at-sign'->after('@')" /> <!-- 'no-at-sign' because there is no @ to cut at -->
$file = 'archive.tar.gz'
echo $file->after('.')          // 'tar.gz' because it cuts at the first dot
echo $file->after('.', last)    // 'gz' because it cuts at the last dot
echo 'no-at-sign'->after('@')   // 'no-at-sign' because there is no @ to cut at
ParâmetroRecebe
text obrigatóriostring
last opcionaluma flag: last ou not last

Os argumentos podem ser nomeados: ->after(…, last: …).

Exemplo
<echo>{ 'joan@example.com'->after('@') }</echo>
echo 'joan@example.com'->after('@')

#string->before(text: string, last?: bool) → string

O texto antes da primeira vez que o texto aparece (ou da última vez, com last), ou o texto inteiro quando ele não aparece: 'a.tar.gz'->before('.', last) é a.tar.

->before(text, last?) retorna o texto antes da primeira vez que text aparece, ou antes da última vez com last. Quando text não está presente, você recebe o texto inteiro de volta:

<let name="email" value="'joan@example.com'" />
<echo value="$email->before('@')" /> <!-- 'joan' -->
<echo value="'archive.tar.gz'->before('.', last)" /> <!-- 'archive.tar' because it cuts at the last dot -->
$email = 'joan@example.com'
echo $email->before('@')                 // 'joan'
echo 'archive.tar.gz'->before('.', last) // 'archive.tar' because it cuts at the last dot
ParâmetroRecebe
text obrigatóriostring
last opcionaluma flag: last ou not last

Os argumentos podem ser nomeados: ->before(…, last: …).

Exemplo
<echo>{ 'joan@example.com'->before('@') }</echo>
echo 'joan@example.com'->before('@')

#string->blocks() → string[]

As partes do texto entre linhas em branco, cada uma sem as quebras de linha ao redor: 'a\nb\n\nc'->blocks() é ['a\nb', 'c'].

->blocks() divide o texto em linhas em branco, então cada bloco é um grupo de linhas. Uma quebra de linha simples fica dentro do bloco; só uma linha vazia começa um novo. Cada bloco perde as quebras de linha ao redor:

<let name="pantry">```text
    tea
    milk

    flour
    sugar
    eggs
    ```</let>

<let name="shelves" value="$pantry->blocks()" />
<echo value="$shelves->count()" /> <!-- 2 because one blank line splits the text in two -->
<echo value="$shelves->map(.lines()->count())" /> <!-- [2, 3] because the first block has 2 lines and the second 3 -->
$pantry = ```text
tea
milk

flour
sugar
eggs
```

$shelves = $pantry->blocks()
echo $shelves->count()                  // 2 because one blank line splits the text in two
echo $shelves->map(.lines()->count())   // [2, 3] because the first block has 2 lines and the second 3
Exemplo
<echo>{ ('a' + @char_of(10) + @char_of(10) + 'b')->blocks() }</echo>
echo ('a' + @char_of(10) + @char_of(10) + 'b')->blocks()

#string->capitalize() → string

O texto com a primeira letra em maiúscula.

->capitalize() deixa a primeira letra em maiúscula e mantém o restante como está:

<echo value="'élan and style'->capitalize()" /> <!-- 'Élan and style' because only the first letter changes -->
<echo value="'iPhone'->capitalize()" /> <!-- 'IPhone' -->
echo 'élan and style'->capitalize()   // 'Élan and style' because only the first letter changes
echo 'iPhone'->capitalize()           // 'IPhone'
Exemplo
<echo>{ 'hello world'->capitalize() }</echo>
echo 'hello world'->capitalize()

#string->case(style: snake|kebab|camel|pascal) → string

O texto como um identificador em um estilo: 'User ID'->case(snake) é user_id, kebab dá user-id, camel dá userId e pascal dá UserId.

->case(style) reescreve o texto como um nome em um estilo: snake (user_id), kebab (user-id), camel (userId) ou pascal (UserId). Ele identifica as palavras separadas por espaços, separadores ou mudanças de maiúscula, então você pode passar de qualquer estilo para qualquer outro:

<echo value="'Order Total'->case(snake)" /> <!-- 'order_total' -->
<echo value="'order_total'->case(camel)" /> <!-- 'orderTotal' -->
<echo value="'orderTotal'->case(kebab)" /> <!-- 'order-total' -->
<echo value="'order-total'->case(pascal)" /> <!-- 'OrderTotal' -->
echo 'Order Total'->case(snake)   // 'order_total'
echo 'order_total'->case(camel)   // 'orderTotal'
echo 'orderTotal'->case(kebab)    // 'order-total'
echo 'order-total'->case(pascal)  // 'OrderTotal'
ParâmetroRecebe
style obrigatóriouma destas palavras: snake|kebab|camel|pascal
Exemplo
<echo>{ 'Order Total'->case(snake) }</echo>
echo 'Order Total'->case(snake)

#string->chars() → string[]

Os caracteres, como uma lista.

->chars() retorna os caracteres como uma lista, um texto para cada um. Um caractere como um emoji é um único item, independentemente de como for armazenado:

<echo value="'tea'->chars()" /> <!-- ['t', 'e', 'a'] -->
<echo value="'👍🏽x'->chars()->count()" /> <!-- 2 because the thumb and its skin tone are one character -->
echo 'tea'->chars()   // ['t', 'e', 'a']
echo '👍🏽x'->chars()->count()   // 2 because the thumb and its skin tone are one character
Exemplo
<echo>{ 'abc'->chars() }</echo>
echo 'abc'->chars()

#string->contains(text, ignore_case?: bool) → bool

True quando o texto contém este texto. Com ignore_case: true, maiúsculas e minúsculas são equivalentes.

->contains(text, ignore_case?) é verdadeiro quando o texto contém text em qualquer posição. Com ignore_case, maiúsculas e minúsculas são equivalentes:

<echo value="'Green tea'->contains('tea')" /> <!-- true -->
<echo value="'Green tea'->contains('TEA')" /> <!-- false because case matters -->
<echo value="'Green tea'->contains('TEA', ignore_case)" /> <!-- true -->
echo 'Green tea'->contains('tea')                // true
echo 'Green tea'->contains('TEA')                // false because case matters
echo 'Green tea'->contains('TEA', ignore_case)   // true
ParâmetroRecebe
text obrigatórioqualquer valor
ignore_case opcionalum indicador: ignore_case ou not ignore_case

Os argumentos podem ser nomeados: ->contains(…, ignore_case: …).

Exemplo
<echo>{ 'hello world'->contains('world') }</echo>
echo 'hello world'->contains('world')

#string->count() → number

O número de caracteres.

->count() retorna quantos caracteres o texto tem:

<echo value="'tea'->count()" /> <!-- 3 -->
<echo value="''->count()" /> <!-- 0 -->
echo 'tea'->count()   // 3
echo ''->count()      // 0
Exemplo
<echo>{ 'hello'->count() }</echo>
echo 'hello'->count()

#string->count_of(match) → number

Quantas vezes um trecho de texto aparece.

->count_of(match) conta quantas vezes um trecho de texto aparece. As ocorrências não se sobrepõem:

<echo value="'banana'->count_of('an')" /> <!-- 2 because b-an-an-a has two -->
<echo value="'banana'->count_of('x')" /> <!-- 0 -->
echo 'banana'->count_of('an')   // 2 because b-an-an-a has two
echo 'banana'->count_of('x')    // 0
Exemplo
<echo>{ 'banana'->count_of('a') }</echo>
echo 'banana'->count_of('a')

#string->ends_with(text, ignore_case?: bool) → bool

Verdadeiro quando o texto termina com este texto. Com ignore_case: true, maiúsculas e minúsculas são equivalentes.

->ends_with(text, ignore_case?) é verdadeiro quando o texto termina com text:

<echo value="'photo.JPG'->ends_with('.jpg')" /> <!-- false because case matters -->
<echo value="'photo.JPG'->ends_with('.jpg', ignore_case)" /> <!-- true -->
echo 'photo.JPG'->ends_with('.jpg')                // false because case matters
echo 'photo.JPG'->ends_with('.jpg', ignore_case)   // true
ParâmetroRecebe
text obrigatórioqualquer valor
ignore_case opcionalum indicador: ignore_case ou not ignore_case

Os argumentos podem ser nomeados: ->ends_with(…, ignore_case: …).

Exemplo
<echo>{ 'notes.txt'->ends_with('.txt') }</echo>
echo 'notes.txt'->ends_with('.txt')

#string->escape() → string

O texto com escape HTML.

->escape() torna o texto seguro para colocar em HTML: <, >, & e aspas viram entidades, então o que um usuário digitou aparece como texto e não como marcação:

<echo value="'&lt;b>Tea &amp; milk&lt;/b>'->escape()" /> <!-- '&lt;b&gt;Tea &amp; milk&lt;/b&gt;' -->
echo '<b>Tea & milk</b>'->escape()   // '&lt;b&gt;Tea &amp; milk&lt;/b&gt;'

As páginas já escapam o que imprimem; isto é para HTML que você mesmo monta.

Exemplo
<echo>{ 'Say "hi" > 3'->escape() }</echo>
echo 'Say "hi" > 3'->escape()

#string->find_all(pattern: regex) → string[]

Cada correspondência de uma expressão regular, como uma lista.

->find_all(pattern) retorna todas as ocorrências de uma expressão regular, em ordem:

<echo value="'tea 12, milk 7'->find_all(/\d+/)" /> <!-- ['12', '7'] because those are the runs of digits -->
echo 'tea 12, milk 7'->find_all(/\d+/)   // ['12', '7'] because those are the runs of digits

->numbers() retorna os próprios números, como números.

ParâmetroRecebe
pattern obrigatórioregex
Exemplo
<echo>{ 'Call 555-1234 or 555-9876'->find_all('[0-9]{3}-[0-9]{4}') }</echo>
echo 'Call 555-1234 or 555-9876'->find_all('[0-9]{3}-[0-9]{4}')

#string->first() → string

O primeiro caractere.

->first() retorna o primeiro caractere, ou '' para um texto vazio:

<echo value="'tea'->first()" /> <!-- 't' -->
<echo value="''->first()" /> <!-- '' -->
echo 'tea'->first()   // 't'
echo ''->first()      // ''
Exemplo
<echo>{ 'Joan'->first() }</echo>
echo 'Joan'->first()

#string->from_base64() → string

Texto Base64 decodificado.

->from_base64() decodifica um texto em base64 de volta ao texto original. Um texto que não está em base64 gera um erro:

<echo value="'dGVh'->from_base64()" /> <!-- 'tea' -->
echo 'dGVh'->from_base64()   // 'tea'
Exemplo
<echo>{ 'aGVsbG8='->from_base64() }</echo>
echo 'aGVsbG8='->from_base64()

#string->grid() → string[][]

O texto como linhas de caracteres, uma lista por linha, para mapas e labirintos: '#.\n.#'->grid() é [['#', '.'], ['.', '#']]. Uma quebra de linha no final não adiciona uma linha vazia. Leia uma célula com $grid[linha][coluna] e percorra suas linhas ou colunas com ->cells(rows) ou ->cells(columns).

->grid() transforma linhas de caracteres em linhas de caracteres únicos, então $grid[row][column] é um único caractere. A linha 0 é a linha de cima e a coluna 0 é o primeiro caractere. Uma quebra de linha no final não adiciona uma linha vazia:

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="plot" value="$garden->grid()" />
<echo value="$plot" /> <!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is #.# and column 1 is its middle -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is ..# and column 2 is its last -->
$garden = ```text
#.#
..#
```

$plot = $garden->grid()
echo $plot          // [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1]    // '.' because row 0 is #.# and column 1 is its middle
echo $plot[1][2]    // '#' because row 1 is ..# and column 2 is its last

Para percorrer as linhas ou as colunas, leia a grade com ->cells(rows) ou ->cells(columns).

Exemplo
<echo>{ ('#.' + @char_of(10) + '.#')->grid() }</echo>
echo ('#.' + @char_of(10) + '.#')->grid()

#string->hmac(key, algorithm?: sha256|sha1|sha512) → string

O HMAC do texto com uma chave secreta, em hexadecimal (SHA-256 por padrão), como são feitas as assinaturas de webhooks. Compare assinaturas com @secure_equals().

->hmac(key, algorithm?) assina o texto com uma chave secreta e retorna a assinatura em hexadecimal, SHA-256 a menos que você passe sha1 ou sha512. É assim que webhooks comprovam a origem de uma mensagem. Compare assinaturas com @secure_equals(), que leva o mesmo tempo independentemente de quanto das duas coincide:

<let name="body" value="'{&quot;id&quot;: 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="$signature->count()" /> <!-- 64 because SHA-256 in hex is 64 characters -->
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true because the same key signs the same text the same way -->
$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo $signature->count()                                    // 64 because SHA-256 in hex is 64 characters
echo @secure_equals($signature, $body->hmac('whsec_test'))  // true because the same key signs the same text the same way
ParâmetroRecebe
key obrigatórioqualquer valor
algorithm opcionaluma destas palavras: sha256|sha1|sha512

Os argumentos podem ser nomeados: ->hmac(…, algorithm: …).

Exemplo
<echo>{ '{"id": 1}'->hmac('whsec_test') }</echo>
echo '{"id": 1}'->hmac('whsec_test')

#string->index_of(text, ignore_case?: bool, last?: bool) → number

A posição onde o texto aparece pela primeira vez, ou com last, onde ele aparece pela última vez; -1 quando não aparece. Com ignore_case, maiúsculas e minúsculas são equivalentes.

->index_of(text, ignore_case?, last?) retorna a posição onde text aparece pela primeira vez, ou com last, onde aparece pela última vez. Retorna -1 quando text não está presente:

<echo value="'banana'->index_of('an')" /> <!-- 1 because positions start at 0 -->
<echo value="'banana'->index_of('an', last)" /> <!-- 3 -->
<echo value="'banana'->index_of('x')" /> <!-- -1 -->
echo 'banana'->index_of('an')         // 1 because positions start at 0
echo 'banana'->index_of('an', last)   // 3
echo 'banana'->index_of('x')          // -1
ParâmetroRecebe
text obrigatórioqualquer valor
ignore_case opcionalum indicador: ignore_case ou not ignore_case
last opcionaluma flag: last ou not last

Os argumentos podem ser nomeados: ->index_of(…, ignore_case: …, last: …).

Exemplo
<echo>{ 'hello'->index_of('l') }</echo>
echo 'hello'->index_of('l')

#string->is_blank() → bool

Verdadeiro quando o texto está vazio ou contém apenas espaços em branco.

->is_blank() é verdadeiro quando o texto está vazio ou tem apenas espaços, tabulações e quebras de linha. Use para verificar o que alguém digitou em um formulário:

<echo value="''->is_blank()" /> <!-- true -->
<echo value="'   '->is_blank()" /> <!-- true because spaces alone count as blank -->
<echo value="' tea '->is_blank()" /> <!-- false -->
echo ''->is_blank()       // true
echo '   '->is_blank()    // true because spaces alone count as blank
echo ' tea '->is_blank()  // false
Exemplo
<echo>{ '   '->is_blank() }</echo>
echo '   '->is_blank()

#string->is_empty() → bool

Verdadeiro quando o texto tem zero caracteres.

->is_empty() é verdadeiro quando o texto não tem nenhum caractere. Espaços contam como caracteres, então ' ' não está vazio; use ->is_blank() para isso:

<echo value="''->is_empty()" /> <!-- true -->
<echo value="'   '->is_empty()" /> <!-- false because it has three spaces -->
echo ''->is_empty()      // true
echo '   '->is_empty()   // false because it has three spaces
Exemplo
<echo>{ ''->is_empty() }</echo>
echo ''->is_empty()

#string->is_numeric() → bool

Verdadeiro quando o texto inteiro é um número, como '42', '-3.5' ou '1e3'. Espaços ao redor são permitidos.

->is_numeric() é verdadeiro quando o texto inteiro é um número, como '42', '-3.5' ou '1e3'. Espaços ao redor são permitidos:

<echo value="'42'->is_numeric()" /> <!-- true -->
<echo value="' -3.5 '->is_numeric()" /> <!-- true because the spaces around it are fine -->
<echo value="'42 cats'->is_numeric()" /> <!-- false because cats isn't part of a number -->
echo '42'->is_numeric()      // true
echo ' -3.5 '->is_numeric()  // true because the spaces around it are fine
echo '42 cats'->is_numeric() // false because cats isn't part of a number
Exemplo
<echo>{ ['42', '-3.5', 'abc']->map(fn(t) => $t->is_numeric()) }</echo>
echo ['42', '-3.5', 'abc']->map(fn(t) => $t->is_numeric())

#string->last() → string

O último caractere.

->last() retorna o último caractere, ou '' para texto vazio:

<echo value="'tea'->last()" /> <!-- 'a' -->
echo 'tea'->last()   // 'a'
Exemplo
<echo>{ 'Joan'->last() }</echo>
echo 'Joan'->last()

#string->lines() → string[]

As linhas do texto, como uma lista.

->lines() retorna um texto por linha. Uma linha em branco gera um texto vazio, para que você possa encontrar as quebras entre grupos:

<let name="note">```text
    tea
    milk

    juice
    ```</let>

<echo value="$note->lines()" /> <!-- ['tea', 'milk', '', 'juice'] -->
<echo value="$note->lines()->count()" /> <!-- 4 because the blank line is a line too -->
$note = ```text
tea
milk

juice
```

echo $note->lines()          // ['tea', 'milk', '', 'juice']
echo $note->lines()->count() // 4 because the blank line is a line too

->blocks() divide nas linhas em branco.

Exemplo
<echo>{ ('one' + @char_of(10) + 'two')->lines() }</echo>
echo ('one' + @char_of(10) + 'two')->lines()

#string->lower() → string

O texto em minúsculas.

->lower() retorna o texto em minúsculas:

<echo value="'Green TEA'->lower()" /> <!-- 'green tea' -->
echo 'Green TEA'->lower()   // 'green tea'
Exemplo
<echo>{ 'HELLO'->lower() }</echo>
echo 'HELLO'->lower()

#string->mask(char?: string, keep_end?: number) → string

O texto com cada caractere substituído por char (* por padrão), exceto os últimos keep_end caracteres: ->mask('*', keep_end: 4) mostra apenas os últimos quatro.

->mask(char?, keep_end?) oculta o texto atrás de um caractere, * a menos que você informe outro, mantendo os últimos keep_end caracteres para que o leitor possa reconhecê-lo:

<echo value="'4242424242424242'->mask('*', keep_end: 4)" /> <!-- '************4242' because only the last 4 show -->
<echo value="'secret'->mask()" /> <!-- '******' -->
echo '4242424242424242'->mask('*', keep_end: 4)   // '************4242' because only the last 4 show
echo 'secret'->mask()                             // '******'
ParâmetroRecebe
char opcionalstring
keep_end opcionalnumber

Os argumentos podem ser nomeados: ->mask(…, keep_end: …).

Exemplo
<echo>{ '4242424242424242'->mask('*', keep_end: 4) }</echo>
echo '4242424242424242'->mask('*', keep_end: 4)

#string->matches(pattern: regex) → bool

Verdadeiro quando o texto corresponde a uma expressão regular: ->matches(/^[a-z]+$/i).

->matches(pattern) é verdadeiro quando uma expressão regular encontra uma correspondência no texto. Ancore com ^ e $ para testar o texto inteiro:

<echo value="'Tea'->matches(/^[a-z]+$/i)" /> <!-- true because i ignores case -->
<echo value="'Tea2'->matches(/^[a-z]+$/i)" /> <!-- false because 2 isn't a letter -->
echo 'Tea'->matches(/^[a-z]+$/i)   // true because i ignores case
echo 'Tea2'->matches(/^[a-z]+$/i)  // false because 2 isn't a letter
ParâmetroRecebe
pattern obrigatórioregex
Exemplo
<echo>{ '2026-11-19'->matches('^[0-9]{4}-[0-9]{2}-[0-9]{2}$') }</echo>
echo '2026-11-19'->matches('^[0-9]{4}-[0-9]{2}-[0-9]{2}$')

#string->md5() → string

O hash MD5 do texto, em hexadecimal.

->md5() retorna o hash MD5 do texto em hexadecimal. É rápido e adequado para uma chave de cache ou um checksum, mas não para senhas ou assinaturas:

<echo value="'tea'->md5()" /> <!-- '7239ea2b5dc943f61f3c0a0276c20974' -->
<echo value="'tea'->md5()->count()" /> <!-- 32 because MD5 in hex is 32 characters -->
echo 'tea'->md5()           // '7239ea2b5dc943f61f3c0a0276c20974'
echo 'tea'->md5()->count()  // 32 because MD5 in hex is 32 characters
Exemplo
<echo>{ 'hello'->md5() }</echo>
echo 'hello'->md5()

#string->normalize_unicode(form?: NFC|NFD|NFKC|NFKD) → string

Normaliza o Unicode usando a forma indicada (NFC por padrão).

->normalize_unicode(form?) faz com que textos que parecem iguais sejam comparados como iguais. é pode ser armazenado como um caractere ou como e mais um acento; NFC (o padrão) os une, NFD os separa:

<echo value="'café'->normalize_unicode(NFD)->count()" /> <!-- 5 because NFD stores é as e and an accent -->
<echo value="'café'->normalize_unicode()->count()" /> <!-- 4 -->
echo 'café'->normalize_unicode(NFD)->count()   // 5 because NFD stores é as e and an accent
echo 'café'->normalize_unicode()->count()      // 4
ParâmetroRecebe
form opcionaluma destas palavras: NFC|NFD|NFKC|NFKD
Exemplo
<echo>{ ('e' + @char_of(769))->normalize_unicode() }</echo>
echo ('e' + @char_of(769))->normalize_unicode()

#string->numbers() → number[]

Cada número do texto, em ordem, como números: 'x=-3, y=12'->numbers() é [-3, 12]. Um sinal de menos torna o número negativo, a menos que uma letra ou dígito venha logo antes dele; assim, '1-3'->numbers() é [1, 3].

->numbers() retorna todos os números escritos no texto, em ordem, como números. Um sinal de menos conta como sinal quando nada está colado à sua esquerda, como em x=-3; entre dois números, como em 1-3, ele é um traço:

<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->
echo 'move 3 boxes from -1 to 12'->numbers()  // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers()                   // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers()           // [2.5, 4]
Exemplo
<echo>{ 'x=-3, y=12'->numbers() }</echo>
echo 'x=-3, y=12'->numbers()

#string->pad(width: number, char?, start?: bool) → string

O texto preenchido no final até width, ou no início com start: '7'->pad(3, '0', start) é 007.

->pad(width, char?, start?) adiciona um caractere, um espaço por padrão, a menos que você informe outro, até que o texto tenha width caracteres. Preenche no final, ou no início com start. Texto que já tem esse tamanho é mantido como está:

<echo value="'7'->pad(3, '0', start)" /> <!-- '007' because two zeros go in front -->
<echo value="'tea'->pad(5, '.')" /> <!-- 'tea..' -->
<echo value="'teapot'->pad(3)" /> <!-- 'teapot' because it is already longer than 3 -->
echo '7'->pad(3, '0', start)   // '007' because two zeros go in front
echo 'tea'->pad(5, '.')        // 'tea..'
echo 'teapot'->pad(3)          // 'teapot' because it is already longer than 3
ParâmetroRecebe
width obrigatórionumber
char opcionalqualquer valor
start opcionaluma flag: start ou not start

Os argumentos podem ser nomeados: ->pad(…, char: …, start: …).

Exemplo
<echo>{ '7'->pad(3, '0', start) }</echo>
echo '7'->pad(3, '0', start)

#string->repeat(count: number) → string

O texto repetido count vezes.

->repeat(count) retorna o texto count vezes:

<echo value="'ha'->repeat(3)" /> <!-- 'hahaha' -->
<echo value="'-'->repeat(10)" /> <!-- '- -- -- -- -- -' -->
echo 'ha'->repeat(3)    // 'hahaha'
echo '-'->repeat(10)    // '----------'
ParâmetroRecebe
count obrigatórionumber
Exemplo
<echo>{ 'ab'->repeat(3) }</echo>
echo 'ab'->repeat(3)

#string->replace(old, new, ignore_case?: bool) → string

O texto com cada old substituído por new. old pode ser uma regex: ->replace(/\s+/, ' '), e new pode usar seus grupos como $1 ou ${name}. Com ignore_case, texto simples casa em qualquer caixa.

->replace(old, new, ignore_case?) substitui cada old por new. old pode ser uma expressão regular, e então new pode usar o que seus grupos capturaram como $1 ou ${name}:

<echo value="'banana'->replace('a', 'o')" /> <!-- 'bonono' because every a changes -->
<echo value="'Tea'->replace('t', 'p', ignore_case)" /> <!-- 'pea' because T matches t -->
<echo value="'too   many  spaces'->replace(/\s+/, ' ')" /> <!-- 'too many spaces' -->
<echo value="'2026-12-01'->replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1')" /> <!-- '01/12/2026' because the groups swap places -->
echo 'banana'->replace('a', 'o')                   // 'bonono' because every a changes
echo 'Tea'->replace('t', 'p', ignore_case)         // 'pea' because T matches t
echo 'too   many  spaces'->replace(/\s+/, ' ')    // 'too many spaces'
echo '2026-12-01'->replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1')   // '01/12/2026' because the groups swap places
ParâmetroRecebe
old obrigatórioqualquer valor
new obrigatórioqualquer valor
ignore_case opcionalum indicador: ignore_case ou not ignore_case

Os argumentos podem ser nomeados: ->replace(…, new: …, ignore_case: …).

Exemplo
<echo>{ 'Hello, World'->replace(old: 'World', new: 'Joan') }</echo>
echo 'Hello, World'->replace(old: 'World', new: 'Joan')

#string->reverse() → string

O texto ao contrário.

->reverse() retorna os caracteres na ordem inversa, mantendo cada caractere inteiro:

<echo value="'stressed'->reverse()" /> <!-- 'desserts' -->
echo 'stressed'->reverse()   // 'desserts'
Exemplo
<echo>{ 'stressed'->reverse() }</echo>
echo 'stressed'->reverse()

#string->sha1() → string

O hash SHA-1 do texto, em hexadecimal. Use-o apenas quando outro sistema exigir SHA-1.

->sha1() retorna o hash SHA-1 do texto em hexadecimal, com 40 caracteres. Prefira ->sha256() para qualquer coisa nova:

<echo value="'tea'->sha1()->count()" /> <!-- 40 -->
echo 'tea'->sha1()->count()   // 40
Exemplo
<echo>{ 'hello'->sha1() }</echo>
echo 'hello'->sha1()

#string->sha256() → string

O hash SHA-256 do texto, em hexadecimal.

->sha256() retorna o hash SHA-256 do texto em hexadecimal, com 64 caracteres. O mesmo texto sempre gera o mesmo hash, e qualquer mudança gera um hash diferente:

<echo value="'tea'->sha256()->count()" /> <!-- 64 -->
<echo value="'tea'->sha256() == 'tea'->sha256()" /> <!-- true because the same text gives the same hash -->
<echo value="'tea'->sha256() == 'Tea'->sha256()" /> <!-- false because one letter changed -->
echo 'tea'->sha256()->count()                  // 64
echo 'tea'->sha256() == 'tea'->sha256()        // true because the same text gives the same hash
echo 'tea'->sha256() == 'Tea'->sha256()        // false because one letter changed
Exemplo
<echo>{ 'hello'->sha256() }</echo>
echo 'hello'->sha256()

#string->sha512() → string

O hash SHA-512 do texto, em hexadecimal.

->sha512() retorna o hash SHA-512 do texto em hexadecimal, com 128 caracteres:

<echo value="'tea'->sha512()->count()" /> <!-- 128 -->
echo 'tea'->sha512()->count()   // 128
Exemplo
<echo>{ 'hello'->sha512()->slice(0, 16) }</echo>
echo 'hello'->sha512()->slice(0, 16)

#string->shapes(mask?: any, square?: bool, rectangle?: bool, line?: bool, circle?: bool, of?: any, rotated?: bool, size?: number, radius?: number, distance?: straight|steps|moves) → list

Every place a mask fits (->shapes(Tree), or ->shapes([Block, Ell]) for several), and every square, rectangle, line or circle (name one or several: ->shapes(square, circle, of: '#')) made by the cells that hold of: (a value, or a regex). It looks through text (each line a row, each character a cell, a blank line between layers), a list of values (one row), a grid ($grid[row][column]) or a 3D list ($cube[layer][row][column]); the built-in shapes also take a list of points { row, column }. A mask is a type that extends Mask: its layout is a picture, one character a cell, and each character matches a cell holding the same character, unless its symbols say otherwise (a value, a regex, a fn(cell), or any for a cell that isn't part of the shape). Each match is { kind, points }: kind is the mask's name or the shape, and each point is { row, column, value } (with symbol for a mask, and layer in 3D). With rotated, a mask is tried turned every way the input allows (back to front in a row, the four quarter turns in a grid, all 24 ways round in 3D), and squares, rectangles and lines may lean. A line needs size:, and a circle radius: and distance: straight (the default), steps or moves.

->shapes(mask?, square?, rectangle?, line?, circle?, of?, rotated?, size?, radius?, distance?) finds shapes drawn in text. Each line is a row and each character a cell, so the text doesn't need ->grid() first, and a blank line starts the next layer of a 3D input. It works as the list method does: name a mask first (a type that extends Mask, or a list of them), or one of the built-in shapes with of: to say which cells make it. Each match comes back as { kind, points }, and each point says its row, column, value and the mask's symbol drawn over it. See list ->shapes() for every argument.

<let name="orchard">```text
    #.#.#
    .#...
    #.#.#
    ```</let>

<type name="Tree" extends="Mask">
  <field name="layout" default="```text
      #.#
      .#.
      ```" />
  <field name="symbols" default="{ '.': any }" />
</type>

<echo value="$orchard->shapes(Tree)->count()" /> <!-- 1 because the V of three trees fits only at the top left -->
<echo value="$orchard->shapes(Tree, rotated)->count()" /> <!-- 4 because turned upside down and on its sides it fits three more places -->
<echo value="$orchard->shapes(Tree)->first().points->map(.column)" /> <!-- [0, 2, 1] because the points come in reading order: the top two, then the middle -->
$orchard = ```text
#.#.#
.#...
#.#.#
```

type Tree extends Mask {
  layout: ```text
    #.#
    .#.
    ```
  symbols: { '.': any }
}

echo $orchard->shapes(Tree)->count()                      // 1 because the V of three trees fits only at the top left
echo $orchard->shapes(Tree, rotated)->count()             // 4 because turned upside down and on its sides it fits three more places
echo $orchard->shapes(Tree)->first().points->map(.column) // [0, 2, 1] because the points come in reading order: the top two, then the middle
ParâmetroRecebe
mask opcionalany
square opcionaluma flag: square ou not square
rectangle opcionaluma flag: rectangle ou not rectangle
line opcionaluma flag: line ou not line
circle opcionaluma flag: circle ou not circle
of opcionalany
rotated opcionaluma flag: rotated ou not rotated
size opcionalnumber
radius opcionalnumber
distance opcionaluma destas palavras: straight|steps|moves

Os argumentos podem ser nomeados: ->shapes(…, square: …, rectangle: …).

Exemplo
<echo>{ ('##' + @char_of(10) + '##')->shapes(square, of: '#')->count() }</echo>
echo ('##' + @char_of(10) + '##')->shapes(square, of: '#')->count()

#string->slice(start: number, end?: number) → string

Parte do texto; posições negativas contam a partir do fim.

->slice(start, end?) retorna os caracteres da posição start até, sem incluir, end, ou até o fim do texto. Posições negativas contam a partir do fim:

<let name="word" value="'teapot'" />
<echo value="$word->slice(0, 3)" /> <!-- 'tea' because it stops before position 3 -->
<echo value="$word->slice(3)" /> <!-- 'pot' -->
<echo value="$word->slice(-3)" /> <!-- 'pot' because -3 is three from the end -->
$word = 'teapot'
echo $word->slice(0, 3)   // 'tea' because it stops before position 3
echo $word->slice(3)      // 'pot'
echo $word->slice(-3)     // 'pot' because -3 is three from the end
ParâmetroRecebe
start obrigatórionumber
end opcionalnumber

Os argumentos podem ser nomeados: ->slice(…, end: …).

Exemplo
<echo>{ 'KScript'->slice(1, 4) }</echo>
echo 'KScript'->slice(1, 4)

#string->split(separator?) → string[]

As partes entre cada separador (ou entre espaços), como uma lista. O separador pode ser uma regex: ->split(/\s*,\s*/).

->split(separator?) corta o texto em cada separador e retorna as partes como uma lista. Sem separador, corta nos espaços. O separador pode ser uma expressão regular:

<echo value="'tea,milk,juice'->split(',')" /> <!-- ['tea', 'milk', 'juice'] -->
<echo value="'tea milk'->split()" /> <!-- ['tea', 'milk'] -->
<echo value="'a, b,c'->split(/\s*,\s*/)" /> <!-- ['a', 'b', 'c'] because the spaces around each comma go too -->
echo 'tea,milk,juice'->split(',')       // ['tea', 'milk', 'juice']
echo 'tea milk'->split()                // ['tea', 'milk']
echo 'a, b,c'->split(/\s*,\s*/)         // ['a', 'b', 'c'] because the spaces around each comma go too
Exemplo
<echo>{ 'a,b,c'->split(',') }</echo>
echo 'a,b,c'->split(',')

#string->squish() → string

O texto sem espaços nas pontas, com cada sequência de espaços, tabulações e quebras de linha internas trocada por um único espaço.

->squish() remove os espaços das pontas do texto e transforma cada sequência de espaços, tabulações e quebras de linha em seu interior em um único espaço:

<echo value="'  too   many    spaces '->squish()" /> <!-- 'too many spaces' -->
echo '  too   many    spaces '->squish()   // 'too many spaces'
Exemplo
<echo>{ '  too   many    spaces '->squish() }</echo>
echo '  too   many    spaces '->squish()

#string->starts_with(text, ignore_case?: bool) → bool

Verdadeiro quando o texto começa com este texto. Com ignore_case: true, maiúsculas e minúsculas são equivalentes.

->starts_with(text, ignore_case?) é verdadeiro quando o texto começa com text:

<echo value="'https://example.com'->starts_with('https://')" /> <!-- true -->
<echo value="'HTTP://x'->starts_with('http', ignore_case)" /> <!-- true because case is ignored -->
echo 'https://example.com'->starts_with('https://')   // true
echo 'HTTP://x'->starts_with('http', ignore_case)     // true because case is ignored
ParâmetroRecebe
text obrigatórioqualquer valor
ignore_case opcionalum indicador: ignore_case ou not ignore_case

Os argumentos podem ser nomeados: ->starts_with(…, ignore_case: …).

Exemplo
<echo>{ 'kscript.json'->starts_with('kscript') }</echo>
echo 'kscript.json'->starts_with('kscript')

#string->strip(prefix?: string, suffix?: string) → string

O texto sem um prefixo, sufixo ou ambos exatos, quando presentes: 'v1.2'->strip(prefix: 'v'), 'a.txt'->strip(suffix: '.txt').

->strip(prefix?, suffix?) remove um prefixo, sufixo ou ambos exatos, quando eles existem. Diferente de ->trim(), remove o trecho inteiro uma vez, não cada caractere:

<echo value="'v1.2'->strip(prefix: 'v')" /> <!-- '1.2' -->
<echo value="'notes.txt'->strip(suffix: '.txt')" /> <!-- 'notes' -->
<echo value="'[tea]'->strip(prefix: '[', suffix: ']')" /> <!-- 'tea' -->
<echo value="'tea'->strip(prefix: 'x')" /> <!-- 'tea' because there is no x to take off -->
echo 'v1.2'->strip(prefix: 'v')                 // '1.2'
echo 'notes.txt'->strip(suffix: '.txt')         // 'notes'
echo '[tea]'->strip(prefix: '[', suffix: ']')   // 'tea'
echo 'tea'->strip(prefix: 'x')                  // 'tea' because there is no x to take off
ParâmetroRecebe
prefix opcionalstring
suffix opcionalstring

Os argumentos podem ser nomeados: ->strip(…, suffix: …).

Exemplo
<echo>{ 'draft-notes.md'->strip(prefix: 'draft-', suffix: '.md') }</echo>
echo 'draft-notes.md'->strip(prefix: 'draft-', suffix: '.md')

#string->title() → string

O texto em Title Case.

->title() devolve o texto em Title Case: a primeira letra de cada palavra em maiúscula:

<echo value="'the tea party'->title()" /> <!-- 'The Tea Party' -->
echo 'the tea party'->title()   // 'The Tea Party'
Exemplo
<echo>{ 'the quick brown fox'->title() }</echo>
echo 'the quick brown fox'->title()

#string->to_base64(url?: bool) → base64

O texto codificado em base64. Com url: true, é base64 seguro para URL sem preenchimento.

->to_base64(url?) codifica o texto em base64, que usa apenas letras, dígitos, +, / e =, para que possa trafegar onde outros caracteres não podem, como um cabeçalho HTTP. Com url, usa - e _ no lugar e omite o preenchimento =, para caber em uma URL. O resultado é um valor base64, cujo ->decode() devolve o texto original:

<echo value="'tea'->to_base64()" /> <!-- 'dGVh' -->
<echo value="'tea?'->to_base64()" /> <!-- 'dGVhPw==' -->
<echo value="'tea?'->to_base64(url)" /> <!-- 'dGVhPw' because url leaves off the padding -->
<echo value="'tea'->to_base64()->decode()" /> <!-- 'tea' because the base64 value decodes back to the text -->
echo 'tea'->to_base64()                 // 'dGVh'
echo 'tea?'->to_base64()                // 'dGVhPw=='
echo 'tea?'->to_base64(url)             // 'dGVhPw' because url leaves off the padding
echo 'tea'->to_base64()->decode()       // 'tea' because the base64 value decodes back to the text
ParâmetroRecebe
url opcionaluma flag: url ou not url
Exemplo
<echo>{ 'hello'->to_base64() }</echo>
echo 'hello'->to_base64()

#string->to_bool() → bool

Texto como 'true', 'false', 'yes', 'no', '1' ou '0' como um bool.

->to_bool() lê texto como 'true', 'false', 'yes', 'no', '1' ou '0' como um bool. Qualquer outro texto gera um erro de Tipo:

<echo value="'yes'->to_bool()" /> <!-- true -->
<echo value="'0'->to_bool()" /> <!-- false -->
echo 'yes'->to_bool()    // true
echo '0'->to_bool()      // false
Exemplo
<echo>{ 'yes'->to_bool() }</echo>
echo 'yes'->to_bool()

#string->to_date(format?: date_format) → date

Lê o texto como uma data: '2026-11-22'->to_date(), ou, conforme a forma escrita, '22-11-2026'->to_date(dd-MM-yyyy).

->to_date(format?) lê texto como data. Datas escritas no formato ISO, como '2026-11-22' ou '2026-11-22 14:30', não precisam de formato; para qualquer outra forma, informe o padrão em que ela está escrita:

<let name="day" value="'2026-11-22'->to_date()" />
<echo value="$day.year" /> <!-- 2026 -->
<echo value="'22-11-2026'->to_date(dd-MM-yyyy).month" /> <!-- 11 because the pattern says the month is in the middle -->
$day = '2026-11-22'->to_date()
echo $day.year                                // 2026
echo '22-11-2026'->to_date(dd-MM-yyyy).month  // 11 because the pattern says the month is in the middle
ParâmetroRecebe
format opcionaldate_format
Exemplo
<echo>{ '2026-11-19'->to_date().weekday }</echo>
echo '2026-11-19'->to_date().weekday

#string->to_int(default?) → number

O texto como um número inteiro, ou default quando não for um.

->to_int(default?) lê texto como um número inteiro, descartando o que vier depois do ponto decimal. Quando o texto não é um número, você obtém default; sem um default, isso gera um erro de Tipo, então informe um default para textos que você não tem certeza de que são numéricos:

<echo value="'42'->to_int()" /> <!-- 42 -->
<echo value="'3.7'->to_int()" /> <!-- 3 because the .7 is dropped -->
<echo value="'abc'->to_int(-1)" /> <!-- -1 because abc isn't a number -->
echo '42'->to_int()        // 42
echo '3.7'->to_int()       // 3 because the .7 is dropped
echo 'abc'->to_int(-1)     // -1 because abc isn't a number
Exemplo
<echo>{ '42'->to_int() + 1 }</echo>
echo '42'->to_int() + 1

#string->to_number(default?) → number

O texto como número, ou default quando não for um.

->to_number(default?) lê texto como número, com casas decimais. Quando o texto não é um número, você obtém default; sem um default, isso gera um erro de Tipo que informa o problema:

<echo value="'3.7'->to_number()" /> <!-- 3.7 -->
<echo value="'x'->to_number(0)" /> <!-- 0 because x isn't a number, so the default is used -->
<echo value="'x'->to_number(null)" /> <!-- null -->
echo '3.7'->to_number()      // 3.7
echo 'x'->to_number(0)       // 0 because x isn't a number, so the default is used
echo 'x'->to_number(null)    // null
Exemplo
<echo>{ '3.5'->to_number() * 2 }</echo>
echo '3.5'->to_number() * 2

#string->trim(characters?, start?: bool, end?: bool) → string

O texto sem espaços (ou os caracteres dados) em uma das extremidades, ou apenas no início ou no fim: ->trim(start), ->trim('/', end).

->trim(characters?, start?, end?) remove espaços, tabulações e quebras de linha de ambas as extremidades, ou os caracteres que você informar. Com start ou end, apara apenas essa extremidade:

<echo value="'  tea  '->trim()" /> <!-- 'tea' -->
<echo value="'//path//'->trim('/')" /> <!-- 'path' -->
<echo value="'  tea  '->trim(start)" /> <!-- 'tea  ' because only the start is trimmed -->
echo '  tea  '->trim()           // 'tea'
echo '//path//'->trim('/')       // 'path'
echo '  tea  '->trim(start)      // 'tea  ' because only the start is trimmed
ParâmetroRecebe
characters opcionalqualquer valor
start opcionaluma flag: start ou not start
end opcionaluma flag: end ou not end

Os argumentos podem ser nomeados: ->trim(…, start: …, end: …).

Exemplo
<echo>{ '  hello  '->trim() + '!' }</echo>
echo '  hello  '->trim() + '!'

#string->truncate(length: number, suffix?) → string

Encurta o texto para length, acrescentando suffix (… por padrão).

->truncate(length, suffix?) mantém os primeiros length caracteres e acrescenta um sufixo, … a menos que você informe outro, quando havia mais texto. Texto que já cabe é deixado como está:

<echo value="'Hello there, friend'->truncate(10)" /> <!-- 'Hello ther…' -->
<echo value="'Hello there, friend'->truncate(10, '...')" /> <!-- 'Hello ther...' -->
<echo value="'Hi'->truncate(10)" /> <!-- 'Hi' because it already fits -->
echo 'Hello there, friend'->truncate(10)          // 'Hello ther…'
echo 'Hello there, friend'->truncate(10, '...')   // 'Hello ther...'
echo 'Hi'->truncate(10)                           // 'Hi' because it already fits
ParâmetroRecebe
length obrigatórionumber
suffix opcionalqualquer valor

Os argumentos podem ser nomeados: ->truncate(…, suffix: …).

Exemplo
<echo>{ 'A long sentence about nothing'->truncate(12) }</echo>
echo 'A long sentence about nothing'->truncate(12)

#string->upper() → string

O texto em letras maiúsculas.

->upper() devolve o texto em letras maiúsculas:

<echo value="'Green tea'->upper()" /> <!-- 'GREEN TEA' -->
echo 'Green tea'->upper()   // 'GREEN TEA'
Exemplo
<echo>{ 'hello'->upper() }</echo>
echo 'hello'->upper()

#string->url_decode() → string

Texto codificado em URL, decodificado.

->url_decode() converte escapes de URL, como %20, de volta nos caracteres que representam:

<echo value="'tea%20%26%20milk'->url_decode()" /> <!-- 'tea & milk' -->
echo 'tea%20%26%20milk'->url_decode()   // 'tea & milk'
Exemplo
<echo>{ 'a%20b%2Fc'->url_decode() }</echo>
echo 'a%20b%2Fc'->url_decode()

#string->url_encode() → string

O texto codificado para uma URL.

->url_encode() escapa o texto para que seja seguro dentro de uma URL, como um termo de busca em uma query string:

<echo value="'tea &amp; milk'->url_encode()" /> <!-- 'tea%20%26%20milk' because spaces and & have a meaning in URLs -->
echo 'tea & milk'->url_encode()   // 'tea%20%26%20milk' because spaces and & have a meaning in URLs
Exemplo
<echo>{ 'a b/c?d'->url_encode() }</echo>
echo 'a b/c?d'->url_encode()

#string->words() → string[]

As palavras do texto, como uma lista, sem espaços ou pontuação. Letras de qualquer escrita contam, e don't ou well-known são uma palavra só.

->words() devolve as palavras do texto, sem os espaços e a pontuação entre elas. Letras de qualquer escrita contam, e don't ou well-known continuam sendo uma palavra só:

<echo value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="&quot;Don't stop&quot;->words()->count()" /> <!-- 2 because don't is one word -->
echo 'Hello, world!'->words()           // ['Hello', 'world']
echo "Don't stop"->words()->count()     // 2 because don't is one word
Exemplo
<echo>{ 'Hello, world! A well-known phrase.'->words() }</echo>
echo 'Hello, world! A well-known phrase.'->words()

#string->wrap(width: number) → string

O texto com quebras de linha entre as palavras, para que nenhuma linha seja maior que width (a menos que uma palavra sozinha seja). Funciona bem com @terminal_width().

->wrap(width) insere quebras de linha entre as palavras para que nenhuma linha seja maior que width, a menos que uma palavra sozinha seja. É útil para texto em um terminal, como um com largura de @terminal_width():

<let name="lines" value="'Ann went home early'->wrap(width: 9)->lines()" />
<echo value="$lines" /> <!-- ['Ann went', 'home', 'early'] because home early would be 10 characters -->
$lines = 'Ann went home early'->wrap(width: 9)->lines()
echo $lines   // ['Ann went', 'home', 'early'] because home early would be 10 characters
ParâmetroRecebe
width obrigatórionumber
Exemplo
<echo>{ 'The quick brown fox jumps over the lazy dog'->wrap(width: 15)->lines() }</echo>
echo 'The quick brown fox jumps over the lazy dog'->wrap(width: 15)->lines()

Do KScript.Markdown

Estes exigem <import package="KScript.Markdown" />import KScript.Markdown. Veja KScript.Markdown.

#string->highlight(lang?: string) → string KScript.Markdown

O código como HTML destacado para um <pre>, colorido com as gramáticas usadas pela extensão do VS Code: cada token em um <span class="hl-kw"> (hl-com, hl-str, hl-num, hl-kw, hl-op, hl-fn, hl-type, hl-var, hl-tag, hl-attr, hl-expr, hl-re) para uma folha de estilos colorir. lang é kscript (o padrão), ks.xml, html (uma página), ks.css, text, ou uma linguagem que o VS Code conhece: css, js, ts, json, sql, sh, yaml, python...
ParâmetroRecebe
lang opcionalstring
Exemplo
<import package="KScript.Markdown" />
<let name="code" value="'$total = $price * 2 // with tax'" />
<echo>{ $code->highlight(lang: 'kscript') }</echo>
import KScript.Markdown
$code = '$total = $price * 2 // with tax'
echo $code->highlight(lang: 'kscript')

#string->markdown_escape() → string KScript.Markdown

O texto escapado para que o Markdown o mostre exatamente como escrito.
Exemplo
<import package="KScript.Markdown" />
<echo>{ '2 * 3 = 6'->markdown_escape() }</echo>
import KScript.Markdown
echo '2 * 3 = 6'->markdown_escape()

Métodos de qualquer tipo

Métodos de number