Contents

Roo

Text.slice()

There are two forms of the slice() method:

First form

text.slice(position as Number) as Text or Nothing

Returns a new Text object containing the character at position. If position is negative then it counts backwards from the end of the text to find the character. The position is zero-based. If position is greater than the length of the text then we return Nothing.

Parameters

  • position. Integer Number. The zero-based position of the character you want returned. If it’s negative then it counts backwards from the end of the text

Returns

  • If position is <= self.length then returns the requested character as a new Text object
  • If position is > self.length then returns Nothing
  • if position is < 0 and the absolute value of position is less than self.length it returns the requested character, counting backwards (i.e: -1 is the last character)

Example

"yes".slice(0) # => "y"
"yes".slice(1) # => "e"
"yes".slice(2) # => "s"
"yes".slice(3) # => Nothing

"yes".slice(-1) # => "s"
"yes".slice(-2) # => "e"
"yes".slice(-3) # => "y"
"yes".slice(-4) # => Nothing

Second form

text.slice(start as Number, length as Number) as Text or Nothing

Returns a new Text object of length length starting from position start. If start is negative then it counts backwards from the end of the text to find the beginning of the text to return. The start position is zero-based. If start is greater than the length of the text then we return Nothing.

Parameters

  • start. Integer Number. The zero-based position of the start of the text you want returned. If it’s negative then it counts backwards from the end of the text
  • length. Integer Number. The number of characters to return

Returns

  • If start <= 0 then returns Nothing
  • If the absolute value of start is greater than the length of this text then raises a runtime error
  • If start < 0 then it counts backwards from the end of the text to find the start position (i.e: -1 is the last character). Returns the text formed between start for length characters. If length > self.length then all characters from the calculated start position to the end of the text are returned

Example

"Hello World".slice(0, 1) # => "H"
"Hello World".slice(0, 3) # => "Hel"
"Hello World".slice(2, 6) # => "llo Wo"
"Hello World".slice(-3, 2) # => "rl"
"Hello World".slice(2, -5) # => Nothing (can't have a negative length)