How to shorten strings?

How do I shorten the string after it reaches the third “minus” symbol from the left to right? It is my first time dealing with string-shortening.

What I want to shorten:

local GUID = "9FB74F07-67DD-4E0F-8C9C-11AD2B85B93D" -- want to remove (-8C9C-11AD2B85B93D)

What I want to end up with:

local ShortenedGUID = "9FB74F07-67DD-4E0F"

There is a nifty little article about string manipulation in the API reference, and it can be very helpful for things like this.

To cutoff the string at the third hyphen, first you need to find the position of the hyphen.
We can do that using the code below:

local GUID = "9FB74F07-67DD-4E0F-8C9C-11AD2B85B93D"

local hyphenPosition = 0
local hyphens = 0
for i=1,#GUID do -- iterate through each character of the string
   if string.sub(GUID,i,i) == "-" then -- if the character is a hyphen
       hyphens = hyphens + 1 -- add to the hyphen counter
       if hyphens = 3 then -- if this is the third hyphen
           hyphenPosition = i -- set hyphen position
           break -- stop looping
       end
   end
end

After we’ve found the third hyphen’s position, we can just cutoff the string right before there. The string.sub function is useful for this.

local shortenedGUID = string.sub(GUID,1,hyphenPosition-1)

Hope this helps!

1 Like

You can use string.split, to get all the things between the hyphens, and then just leave out the last two, like this, then reconstruct the string:

local segments = string.split(GUID, "-")
table.remove(segments, 4)
table.remove(segments, 4)
local ShortenedGUID = table.concat(segments, "-")

Hope I helped! If I made any mistakes, please tell me.

Edit: If you’re wondering why I’m doing table.remove(segments, 4) twice, it’s because if I remove it once, the 5th element gets pushed to the 4th slot.

1 Like

Considering it’s a GUID, it’s always gonna be 8 chars, dash, 4 chars, dash, 4 chars, dash, 4 chars, dash, 12 chars. There’s no reason to over-complicate this, just do GUID:sub(1, 18)

4 Likes

That’s super overcomplicated. Even if GUIDs weren’t guaranteed to fit a specific format, you could accomplish the same thing without a loop in one line. Quick example:

local ShortenedGUID = GUID:match("^([^%-]+%-[^%-]+%-[^%-]+)")
4 Likes