Tagscript

SliceParser

Cut a substring out of a piece of text.

slice returns part of the payload, using character positions counted from 0.

For template authors

Syntax

{slice(start):text}
{slice(start-end):text}
{slice(start,end):text}

With one number you get everything from that position onwards. With two you get everything from the first up to, but not including, the second. Both - and , work as the separator.

Examples

{slice(3):Hello World}
# lo World

{slice(0-5):Hello World}
# Hello

{slice(0,5):Hello World}
# Hello

Trimming a value to a maximum length is the common use:

{slice(0-100):{args}}

Aliases

slice, substr, substring

For developers

Register the parser

import { Interpreter, SliceParser } from 'tagscript';
const ts = new Interpreter(new SliceParser());

Behaviour

Both the parameter and the payload are required. parse calls String.prototype.slice, so a position past the end of the text returns an empty string instead of throwing.

Negative positions do not work. The parser treats - as the range separator before it reads the numbers, so {slice(-5):Hello World} parses as the range ("", "5") and renders Hello rather than the last five characters. Use , and a positive position, or write your own parser, if you need to count from the end.

Note that positions here start at 0, while StringTransformer counts words from 1.

API reference

SliceParser

Last updated on

On this page

Edit on Github