Splitting a string based on capitalisation

Aight, I’ve ran into something I’m fairly curious about and I’m sure would soon arise to be a problem for me. I’ve never been great with string functions etc, so sorry if this is quite an obvious question:

How can I split a string (with spaces) based on capitalisation? For example:

Here I have a bunch of Items who’s names are joined together for easy script access. However when displaying the Item name to the screen I’d like it to be spaced out for better readability.
(CandyBar would be shown as Candy Bar, WoodenSword as Wooden Sword… you get the idea.)

The answer would be to insert a space before each capital letter (there are other ways but I’d like to have this process be done automatically) but I have no clue how I’d do this with roblox’s string functions. If anyone can help I’d greatly appreciate it :slight_smile:

(Never posted this many questions in 1 week lol)

I don’t think there’s a specific method you can use to split it by capitals (someone correct me if I’m wrong), you may need to use a for loop to loop through the string and check each index.

function SplitStringByCapitalLetters(String)
    return string.sub(string.gsub(String, "(%u)", " %1"), 2, -1)

local String = "TestString"
String = SplitStringByCapitalLetters(String)

make sure to check out this link, I think it is very interesting https://scriptinghelpers.org/questions/114766/how-to-split-string-by-capital-letters

anyways i hope I helped out

you can change the function name to whatever


Exactly what I’m looking for, thanks for the help :sunglasses: