@rbxts/jsnatives
slice
Extracts a section of a string and returns it as a new string.
Signature
function slice(str: string, start?: NumericAdmissible, end?: NumericAdmissible): string
Description
The slice
function extracts a section of a string and returns it as a new string, without modifying the original string. The extracted portion starts at the start
index and ends at, but does not include, the end
index.
Parameters
str
: The string to extract from.start
(optional): The zero-based index at which to begin extraction. If a string is provided, it will be converted to a number. If omitted, extraction starts from the beginning of the string (index 0).end
(optional): The zero-based index before which to end extraction. If a string is provided, it will be converted to a number. If omitted, extraction continues to the end of the string.
Return value
- A new string containing the extracted section of the string.
Examples
Basic usage
// Extract a substringconst str = "Hello world";const world = String.slice(str, 6);print(world); // Outputs: "world"
const hello = String.slice(str, 0, 5);print(hello); // Outputs: "Hello"
Using negative indices
// Negative indices count from the end of the stringconst str = "Hello world";const last5 = String.slice(str, -5);print(last5); // Outputs: "world"
const excludeLast = String.slice(str, 0, -1);print(excludeLast); // Outputs: "Hello worl"
Using string indices
// String indices are converted to numbersconst str = "Hello world";const portion = String.slice(str, "1", "5");print(portion); // Outputs: "ello"
Edge cases
const str = "Hello world";
// If start > end, an empty string is returnedconst emptyResult = String.slice(str, 5, 2);print(emptyResult); // Outputs: "" (empty string)
// If start > string length, an empty string is returnedconst beyondLength = String.slice(str, 20);print(beyondLength); // Outputs: "" (empty string)
// If end > string length, extraction continues to the endconst toEnd = String.slice(str, 6, 100);print(toEnd); // Outputs: "world"
Using without parameters
// Without parameters, the entire string is returnedconst str = "Hello world";const copy = String.slice(str);print(copy); // Outputs: "Hello world"
Common slicing patterns
const str = "Hello world";
// Get first 5 charactersconst first5 = String.slice(str, 0, 5);print(first5); // Outputs: "Hello"
// Get last 5 charactersconst last5 = String.slice(str, -5);print(last5); // Outputs: "world"
// Remove first characterconst withoutFirst = String.slice(str, 1);print(withoutFirst); // Outputs: "ello world"
// Remove last characterconst withoutLast = String.slice(str, 0, -1);print(withoutLast); // Outputs: "Hello worl"