Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I target a certain part of a string?

Asked by
L43Q 48
8 years ago

Let's say I have a textbox, and a user has typed something into the textbox. How would I target, for example, the first 6 letters of the string?

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

A portion of a string is called a substring. You can get substrings of a string using the string.sub method.

For example, to get the first six characters of "text":

local text = "abc123xyz"
print( text:sub(1, 6) ) -- abc123

:sub(from, to) gives you the piece of the string starting with the fromth character and ending with the toth character -- that's inclusive.

Thus the ith character is text:sub(i, i). So the first character is text:sub(1, 1).

The to is optional. If you don't specify it, then it takes every from from to the end of the string. For example, text:sub(5) in the above would be "23xyz"


It's often helpful to know how long a string is. You can use either #text or text:len().


string.sub let's you use negative numbers for from and to.

-1is the last character in the string,-2is the second to last, etc. Thustext:sub(-3, -1)` is the last three characters of the string.

0
This was really useful. Thanks L43Q 48 — 8y
Ad

Answer this question