How would I abbreviate a string?

Hello, In my game people have the option to create their own company.
And they will input a name, how would I make turn that name into an Acronym.

For example:
Motor Inc = MI
DJ’s Boats Inc = DBI

How would I go about this?

1 Like

For some reason I suck at getting a string pattern out of this so something like splitting by space and getting the first letter of each word will work.

local str = "DJ's Boats Inc"
local abbreviation = ""

for _, word in ipairs(str:split(" ")) do
    abbreviation ..= word:sub(1, 1)
end

print(abbreviation)
3 Likes

I’ve never seen the use of …=

Can you explain what that does?

Luau introduces several compound operators, +=, -=, *=, /=, %=, ^=, and ..=. If you’ve used Python, JavaScript, etc. you should be familiar with how those work.

a ..= b is the same as a = a .. b

Oh, that is really nice to know. I only knew about += -=. Thanks

If you are interested in pattern for that, here it is

local Default = "DJ's Super Club"

local Result = string.gsub(Default, '(%a)%S*%s*', string.upper)

print(Result)

(%a) for any alphabetic letter, it’s in bracket so string.upper receives it as a first argument
%S* for any string, * is to make it optional to support one letter words
%s* is for whitespaces, * again to make the whitespace optional if word is at end of string

string.upper can be replaced with "%1", it will prevent it from being uppercase all the time. %1 will refer to first match in bracket, any %a in this case.

2 Likes

Important thing, use TextService:FilterStringAsync() on the acronym before accepting it so that players don’t go around creating bad words with their company acronyms.