KScript docs
EN

string fields and methods

Text. A string that holds a number can use number methods too.

Text is a string: anything in quotes. 'Single quotes' keep what you write exactly as it is, and "double quotes" fill in what is in { }, so "Hello { $name }" reads the variable. For text over several lines, write a text block between ``` lines, which keeps every line break as written.

Text methods never change the text they are called on; each gives new text (or a number, a list or a bool), so chain them or keep the result in a variable:

<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

Positions count from 0, and a negative position counts from the end. A character such as an emoji counts as two places, and no method cuts one in half. Comparisons match case exactly unless you pass the ignore_case flag.

Find out about text: count · count_of · is_empty · is_blank · is_numeric · contains · starts_with · ends_with · index_of · matches

Take part of it: first · last · slice · before · after · truncate · find_all

Tidy and change it: trim · squish · strip · replace · upper · lower · capitalize · title · case · pad · repeat · reverse · wrap · mask · normalize_unicode

Break it into a list: split · lines · blocks · words · chars · numbers · grid · shapes

Read it as another value: to_number · to_int · to_bool · to_date, or another format with ->convert()

Make it safe to send: escape · url_encode · url_decode · to_base64 · from_base64 · md5 · sha1 · sha256 · sha512 · hmac

A field is a plain fact about the value, read with a dot and no brackets: $value.name. A method takes arguments or does work, and is called with ->: $value->name(arguments), or with the value piped in: $value |> name(arguments).

From KScript.Core

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

The text after the first time text occurs (or the last time, with last), or the whole text when it doesn't: 'a.tar.gz'->after('.', last) is gz.

->after(text, last?) gives the text after the first time text occurs, or after the last time with last. When text isn't there, you get the whole text back:

<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
ParameterTakes
text requiredstring
last optionala flag: last or not last

Arguments can be named: ->after(…, last: …).

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

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

The text before the first time text occurs (or the last time, with last), or the whole text when it doesn't: 'a.tar.gz'->before('.', last) is a.tar.

->before(text, last?) gives the text before the first time text occurs, or before the last time with last. When text isn't there, you get the whole text back:

<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
ParameterTakes
text requiredstring
last optionala flag: last or not last

Arguments can be named: ->before(…, last: …).

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

#string->blocks() → string[]

The parts of the text between blank lines, each trimmed of the line breaks around it: 'a\nb\n\nc'->blocks() is ['a\nb', 'c'].

->blocks() splits the text at blank lines, so each block is a group of lines. A single line break stays inside a block; only an empty line starts a new one. Each block is trimmed of the line breaks around it:

<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
Example
<echo>{ ('a' + @char_of(10) + @char_of(10) + 'b')->blocks() }</echo>
echo ('a' + @char_of(10) + @char_of(10) + 'b')->blocks()

#string->capitalize() → string

The text with its first letter upper-cased.

->capitalize() makes the first letter upper case and leaves the rest as it is:

<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'
Example
<echo>{ 'hello world'->capitalize() }</echo>
echo 'hello world'->capitalize()

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

The text as an identifier in one style: 'User ID'->case(snake) is user_id, kebab gives user-id, camel userId and pascal UserId.

->case(style) rewrites text as a name in one style: snake (user_id), kebab (user-id), camel (userId) or pascal (UserId). It finds the words in spaces, separators and changes of case alike, so you can go from any style to any other:

<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'
ParameterTakes
style requiredone of these words: snake|kebab|camel|pascal
Example
<echo>{ 'Order Total'->case(snake) }</echo>
echo 'Order Total'->case(snake)

#string->chars() → string[]

The characters, as a list.

->chars() gives the characters as a list, one text each. A character such as an emoji is one item, however it is stored:

<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
Example
<echo>{ 'abc'->chars() }</echo>
echo 'abc'->chars()

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

True when the text contains this text. With ignore_case: true, upper and lower case match.

->contains(text, ignore_case?) is true when the text holds text anywhere. With ignore_case, upper and lower case match:

<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
ParameterTakes
text requiredany value
ignore_case optionala flag: ignore_case or not ignore_case

Arguments can be named: ->contains(…, ignore_case: …).

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

#string->count() → number

The number of characters.

->count() gives how many characters the text has:

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

#string->count_of(match) → number

How many times a piece of text occurs.

->count_of(match) counts how many times a piece of text occurs. Occurrences don't overlap:

<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
Example
<echo>{ 'banana'->count_of('a') }</echo>
echo 'banana'->count_of('a')

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

True when the text ends with this text. With ignore_case: true, upper and lower case match.

->ends_with(text, ignore_case?) is true when the text ends with 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
ParameterTakes
text requiredany value
ignore_case optionala flag: ignore_case or not ignore_case

Arguments can be named: ->ends_with(…, ignore_case: …).

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

#string->escape() → string

The text HTML-escaped.

->escape() makes text safe to put in HTML: <, >, & and quotes become entities, so what a user typed shows as text rather than becoming markup:

<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;'

Pages escape what they print already; this is for HTML you build yourself.

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

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

Every match of a regular expression, as a list.

->find_all(pattern) gives every match of a regular expression, in order:

<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() gives the numbers themselves, as numbers.

ParameterTakes
pattern requiredregex
Example
<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

The first character.

->first() gives the first character, or '' for empty text:

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

#string->from_base64() → string

Base64 text decoded.

->from_base64() decodes base64 text back into the text it was made from. Text that isn't base64 is an error:

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

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

The text as rows of characters, one list per line, for maps and mazes: '#.\n.#'->grid() is [['#', '.'], ['.', '#']]. A line break at the end adds no empty row. Read a cell with $grid[row][column], and go through its rows or columns with ->cells(rows) or ->cells(columns).

->grid() turns lines of characters into rows of single characters, so $grid[row][column] is one character. Row 0 is the top line and column 0 the first character. A line break at the end adds no empty row:

<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

To go through the rows or the columns, read the grid with ->cells(rows) or ->cells(columns).

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

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

The HMAC of the text with a secret key, in hex (SHA-256 by default), as webhook signatures are made. Compare signatures with @secure_equals().

->hmac(key, algorithm?) signs the text with a secret key and gives the signature in hex, SHA-256 unless you pass sha1 or sha512. It is how webhooks prove where a message came from. Compare signatures with @secure_equals(), which takes the same time however much of the two matches:

<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
ParameterTakes
key requiredany value
algorithm optionalone of these words: sha256|sha1|sha512

Arguments can be named: ->hmac(…, algorithm: …).

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

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

Where text first occurs, or with last, where it last occurs; -1 when it doesn't. With ignore_case, upper and lower case match.

->index_of(text, ignore_case?, last?) gives the position where text first occurs, or with last, where it last occurs. It gives -1 when text isn't there:

<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
ParameterTakes
text requiredany value
ignore_case optionala flag: ignore_case or not ignore_case
last optionala flag: last or not last

Arguments can be named: ->index_of(…, ignore_case: …, last: …).

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

#string->is_blank() → bool

True when the text is empty or contains only whitespace.

->is_blank() is true when the text is empty or has only spaces, tabs and line breaks. Use it to check what someone typed into a form:

<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
Example
<echo>{ '   '->is_blank() }</echo>
echo '   '->is_blank()

#string->is_empty() → bool

True when the text has zero characters.

->is_empty() is true when the text has no characters at all. Spaces count as characters, so ' ' isn't empty; use ->is_blank() for that:

<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
Example
<echo>{ ''->is_empty() }</echo>
echo ''->is_empty()

#string->is_numeric() → bool

True when the whole text is a number, such as '42', '-3.5' or '1e3'. Spaces around it are allowed.

->is_numeric() is true when the whole text is a number, such as '42', '-3.5' or '1e3'. Spaces around it are allowed:

<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
Example
<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

The last character.

->last() gives the last character, or '' for empty text:

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

#string->lines() → string[]

The lines of the text, as a list.

->lines() gives one text per line. A blank line gives an empty text, so you can find the breaks between groups:

<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() splits at the blank lines instead.

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

#string->lower() → string

The text in lower case.

->lower() gives the text in lower case:

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

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

The text with each character replaced by char (* by default), apart from the last keep_end characters: ->mask('*', keep_end: 4) shows only the last four.

->mask(char?, keep_end?) hides the text behind a character, * unless you give another, keeping the last keep_end characters so the reader can recognise it:

<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()                             // '******'
ParameterTakes
char optionalstring
keep_end optionalnumber

Arguments can be named: ->mask(…, keep_end: …).

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

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

True when the text matches a regular expression: ->matches(/^[a-z]+$/i).

->matches(pattern) is true when a regular expression finds a match in the text. Anchor it with ^ and $ to test the whole text:

<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
ParameterTakes
pattern requiredregex
Example
<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

The MD5 hash of the text, in hex.

->md5() gives the MD5 hash of the text in hex. It is quick and fine for a cache key or a checksum, but not for passwords or signatures:

<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
Example
<echo>{ 'hello'->md5() }</echo>
echo 'hello'->md5()

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

Normalizes Unicode using the given form (NFC by default).

->normalize_unicode(form?) makes text that looks the same compare the same. é can be stored as one character or as e plus an accent; NFC (the default) joins them, NFD splits them:

<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
ParameterTakes
form optionalone of these words: NFC|NFD|NFKC|NFKD
Example
<echo>{ ('e' + @char_of(769))->normalize_unicode() }</echo>
echo ('e' + @char_of(769))->normalize_unicode()

#string->numbers() → number[]

Every number in the text, in order, as numbers: 'x=-3, y=12'->numbers() is [-3, 12]. A minus makes a number negative unless a letter or digit comes right before it, so '1-3'->numbers() is [1, 3].

->numbers() gives every number written in the text, in order, as numbers. A minus counts as a sign when nothing is joined to its left, as in x=-3; between two numbers, as in 1-3, it is a dash:

<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]
Example
<echo>{ 'x=-3, y=12'->numbers() }</echo>
echo 'x=-3, y=12'->numbers()

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

The text padded at the end to width, or at the start with start: '7'->pad(3, '0', start) is 007.

->pad(width, char?, start?) adds a character, a space unless you give another, until the text is width characters long. It pads at the end, or at the start with start. Text already that long is left alone:

<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
ParameterTakes
width requirednumber
char optionalany value
start optionala flag: start or not start

Arguments can be named: ->pad(…, char: …, start: …).

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

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

The text repeated count times.

->repeat(count) gives the text count times over:

<echo value="'ha'->repeat(3)" /> <!-- 'hahaha' -->
<echo value="'-'->repeat(10)" /> <!-- '- -- -- -- -- -' -->
echo 'ha'->repeat(3)    // 'hahaha'
echo '-'->repeat(10)    // '----------'
ParameterTakes
count requirednumber
Example
<echo>{ 'ab'->repeat(3) }</echo>
echo 'ab'->repeat(3)

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

The text with every old replaced by new. old can be a regex: ->replace(/\s+/, ' '), and new can use its groups as $1 or ${name}. With ignore_case, plain text matches in any case.

->replace(old, new, ignore_case?) replaces every old with new. old can be a regular expression, and then new can use what its groups matched as $1 or ${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
ParameterTakes
old requiredany value
new requiredany value
ignore_case optionala flag: ignore_case or not ignore_case

Arguments can be named: ->replace(…, new: …, ignore_case: …).

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

#string->reverse() → string

The text backwards.

->reverse() gives the characters in the opposite order, keeping each character whole:

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

#string->sha1() → string

The SHA-1 hash of the text, in hex. Use it only where another system asks for SHA-1.

->sha1() gives the SHA-1 hash of the text in hex, 40 characters. Prefer ->sha256() for anything new:

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

#string->sha256() → string

The SHA-256 hash of the text, in hex.

->sha256() gives the SHA-256 hash of the text in hex, 64 characters. The same text always gives the same hash, and any change gives a different one:

<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
Example
<echo>{ 'hello'->sha256() }</echo>
echo 'hello'->sha256()

#string->sha512() → string

The SHA-512 hash of the text, in hex.

->sha512() gives the SHA-512 hash of the text in hex, 128 characters:

<echo value="'tea'->sha512()->count()" /> <!-- 128 -->
echo 'tea'->sha512()->count()   // 128
Example
<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, repeated?: bool, blank?: any) → 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), same for cells that all hold one value, or any for a cell that isn't part of the shape). A layout can be a regex too, which reads cells along a row, any length. With repeated, the mask is stamped again and again from the top left until it covers the input, the copies at the edges cut off: every copy must hold what the first does, and each match is the first copy, with copies, how many there were (a regex layout gives one match per size that fits, smallest first). blank: (a value, a regex or a fn(cell)) names the input cells that fit anything, and copies and same cells fill each other's blanks in. 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?, repeated?, blank?) 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. A mask's layout can be a regex, which reads along each line, any length. repeated stamps the mask over the whole text and gives the first copy, and blank: '?' lets the ?s fit anything. See list ->shapes() for every argument, and masks for the guide.

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

<type name="Instructions" description="A printer's instructions: one or more colours." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<echo value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first().points->count()" /> <!-- 3 because rgb, repeated and cut off, prints the whole barcode -->
<echo value="'?rv'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 2 because vr fits: the ? is a v -->
$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

/// A printer's instructions: one or more colours.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

echo 'rgbrgbrgbr'->shapes(Instructions, repeated)->first().points->count()   // 3 because rgb, repeated and cut off, prints the whole barcode
echo '?rv'->shapes(Instructions, repeated, blank: '?')->first().points->count() // 2 because vr fits: the ? is a v
ParameterTakes
mask optionalany
square optionala flag: square or not square
rectangle optionala flag: rectangle or not rectangle
line optionala flag: line or not line
circle optionala flag: circle or not circle
of optionalany
rotated optionala flag: rotated or not rotated
size optionalnumber
radius optionalnumber
distance optionalone of these words: straight|steps|moves
repeated optionala flag: repeated or not repeated
blank optionalany

Arguments can be named: ->shapes(…, square: …, rectangle: …).

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

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

Part of the text; negative positions count from the end.

->slice(start, end?) gives the characters from position start up to, but not including, end, or to the end of the text. Negative positions count from the end:

<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
ParameterTakes
start requirednumber
end optionalnumber

Arguments can be named: ->slice(…, end: …).

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

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

The parts between each separator (or between spaces), as a list. The separator can be a regex: ->split(/\s*,\s*/).

->split(separator?) cuts the text at each separator and gives the parts as a list. Without a separator it cuts at spaces. The separator can be a regular expression:

<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
Example
<echo>{ 'a,b,c'->split(',') }</echo>
echo 'a,b,c'->split(',')

#string->squish() → string

The text trimmed, with each run of spaces, tabs and line breaks inside made one space.

->squish() trims the text and makes every run of spaces, tabs and line breaks inside it one space:

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

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

True when the text starts with this text. With ignore_case: true, upper and lower case match.

->starts_with(text, ignore_case?) is true when the text begins with 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
ParameterTakes
text requiredany value
ignore_case optionala flag: ignore_case or not ignore_case

Arguments can be named: ->starts_with(…, ignore_case: …).

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

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

The text without one exact prefix, suffix or both, where present: 'v1.2'->strip(prefix: 'v'), 'a.txt'->strip(suffix: '.txt').

->strip(prefix?, suffix?) takes off one exact prefix, suffix or both, where they are there. Unlike ->trim() it removes the whole piece once, not each character:

<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
ParameterTakes
prefix optionalstring
suffix optionalstring

Arguments can be named: ->strip(…, suffix: …).

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

#string->title() → string

The text in Title Case.

->title() gives the text in Title Case: the first letter of each word upper case:

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

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

The text encoded as base64. With url: true, it is URL-safe base64 without padding.

->to_base64(url?) encodes text as base64, which uses only letters, digits, +, / and =, so it can travel where other characters can't, such as an HTTP header. With url, it uses - and _ instead and leaves off the = padding, so it fits in a URL. The result is a base64 value, whose ->decode() gives the text back:

<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
ParameterTakes
url optionala flag: url or not url
Example
<echo>{ 'hello'->to_base64() }</echo>
echo 'hello'->to_base64()

#string->to_bool() → bool

Text such as 'true', 'false', 'yes', 'no', '1' or '0' as a bool.

->to_bool() reads text such as 'true', 'false', 'yes', 'no', '1' or '0' as a bool. Any other text is a Type error:

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

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

Reads the text as a date: '2026-11-22'->to_date(), or with the way it is written, '22-11-2026'->to_date(dd-MM-yyyy).

->to_date(format?) reads text as a date. Dates written the ISO way, such as '2026-11-22' or '2026-11-22 14:30', need no format; for any other way, give the pattern it is written in:

<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
ParameterTakes
format optionaldate_format
Example
<echo>{ '2026-11-19'->to_date().weekday }</echo>
echo '2026-11-19'->to_date().weekday

#string->to_int(default?) → number

The text as a whole number, or default when it isn't one.

->to_int(default?) reads text as a whole number, dropping anything after the decimal point. When the text isn't a number, you get default; without one, that is a Type error, so pass a default for text you aren't sure of:

<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
Example
<echo>{ '42'->to_int() + 1 }</echo>
echo '42'->to_int() + 1

#string->to_number(default?) → number

The text as a number, or default when it isn't one.

->to_number(default?) reads text as a number, decimals and all. When the text isn't a number, you get default; without one, that is a Type error that says so:

<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
Example
<echo>{ '3.5'->to_number() * 2 }</echo>
echo '3.5'->to_number() * 2

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

The text without spaces (or the given characters) at either end, or only at the start or the end: ->trim(start), ->trim('/', end).

->trim(characters?, start?, end?) takes spaces, tabs and line breaks off both ends, or the characters you give. With start or end it trims only that end:

<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
ParameterTakes
characters optionalany value
start optionala flag: start or not start
end optionala flag: end or not end

Arguments can be named: ->trim(…, start: …, end: …).

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

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

Shortens the text to length, adding suffix (… by default).

->truncate(length, suffix?) keeps the first length characters and adds a suffix, … unless you give another, when there was more. Text that already fits is left alone:

<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
ParameterTakes
length requirednumber
suffix optionalany value

Arguments can be named: ->truncate(…, suffix: …).

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

#string->upper() → string

The text in upper case.

->upper() gives the text in upper case:

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

#string->url_decode() → string

URL-escaped text decoded.

->url_decode() turns URL escapes such as %20 back into the characters they stand for:

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

#string->url_encode() → string

The text escaped for a URL.

->url_encode() escapes text so it is safe inside a URL, such as a search term in a 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
Example
<echo>{ 'a b/c?d'->url_encode() }</echo>
echo 'a b/c?d'->url_encode()

#string->words() → string[]

The words in the text, as a list, without spaces or punctuation. Letters in any script count, and don't or well-known is one word.

->words() gives the words in the text, without the spaces and punctuation between them. Letters in any script count, and don't or well-known stay one word:

<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
Example
<echo>{ 'Hello, world! A well-known phrase.'->words() }</echo>
echo 'Hello, world! A well-known phrase.'->words()

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

The text with line breaks between words so no line is longer than width (unless one word is). Works well with @terminal_width().

->wrap(width) puts line breaks between words so that no line is longer than width, unless a single word is. It suits text for a terminal, such as one @terminal_width() wide:

<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
ParameterTakes
width requirednumber
Example
<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()

From KScript.Markdown

These need <import package="KScript.Markdown" />import KScript.Markdown. See KScript.Markdown.

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

The code as highlighted HTML for a <pre>, coloured with the grammars the VS Code extension uses: each token in a <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) for a stylesheet to colour. lang is kscript (the default), ks.xml, html (a page), ks.css, text, or a language VS Code knows: css, js, ts, json, sql, sh, yaml, python...
ParameterTakes
lang optionalstring
Example
<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

The text escaped so Markdown shows it as written.
Example
<import package="KScript.Markdown" />
<echo>{ '2 * 3 = 6'->markdown_escape() }</echo>
import KScript.Markdown
echo '2 * 3 = 6'->markdown_escape()

Methods from any

Methods from number