Splitting a string

Hey developers,

I’ve been working on a custom chat recently, and am currently working on a whisper via “/w (username)”.
I’m wondering what the best way to split the text would be so Instead of having one string, I have the original, and then whatever goes after "/w "
I also need the message that comes after the username.
What’s the best way to accomplish this?

MessageBox:GetPropertyChangedSignal("Text"):Connect(function()
	if MessageBox.Text:split(" ")[1] == "/w" and MessageBox.Text:split(" ")[2] ~= nil then
	    local matches = {}
	    for i, Player in ipairs(game.Players:GetPlayers()) do
	        local name = Player.Name
	        local term = string.sub(name, 3,string.len(MessageBox.Text:split(" ")[2]))
	        
			local match = string.find(term:lower(), MessageBox.Text:lower())
	
	        if match then
				            table.insert(matches, name)
				print(match,name)
	        end
	    end
	    
	    if #matches == 1 then
	        MessageBox.Text = matches[1]
		end
	end
end)

Is there any wrong way per say? If there is, why is that so?

1 Like

You can use string.find to find the first occurance of space:

local from, to = MessageBox.Text:find("%s+")
-- %s refers to any whitespace, + means any amount
-- so `/w   something else` would find the three spaces
-- from and to are the bounds (positions) of the found substring

Then use string.sub to cut out the pieces:

local command = MessageBox.Text:sub(1, from - 1)
-- from beginning to character left to the space(s)

local arguments = MessageBox.Text:sub(to + 1)
-- from the character right to the space(s) to the end

You can repeat this process with the remaining arguments to perform another split and get the username.

2 Likes

I’d just do your :split method once, and save the table to a variable. There’s no point running split on the same string again and again every time you need another item from the table.

1 Like

How is this different from just using string.split(" ")?

It performs a single “split” along the first occurance of the search string / pattern and it allows to split along multiple spaces (if you use "%s+". you can use " " instead if you only want to split along a single space).

1 Like