Allow 1 space per word, remove leading and trailing spaces in a TextBox

I’m currently making plugin, and for it to work perfectly, I need to do following things to TextBoxes:

  1. Remove trailing and leading spaces (I know how to do this, but is there a way to combine the pattern?)

  2. Allow only 1 space per word

I’ll write [n spaces] because I cant write more that 1 space per word here.
For example:
a[2 spaces]ba[1 space]b (remove 1 space as there were 2 spaces)
a[1 spaces]ba[1 space]b (no changes as there was 1 space)
[1 space]a[3 spaces]b[4 spaces][0 spaces]a[1 space]b[0 spaces] (remove leading and trailing spaces + remove 2 spaces between a and b as there were 3 spaces)

Note that TextBox is not limited to 2 words in my plugin.

You can make it like this:

local Text = "       Hello     this        is      test!!!        "
local NewText = Text:gsub(" +", " "):gsub("^%s+", ""):gsub("%s+$", "")
print(NewText)

Output: "Hello this is test!!!"

Text:gsub(" +", " ") --> remove multiple spaces in a row on 1
Text:gsub("^%s+", "") --> remove space on start
Text:gsub("%s+$", "") --> remove space on end
local textbox = script.Parent

textbox:GetPropertyChangedSignal("Text"):Connect(function()
	local text = textbox.Text
	text = text:gsub("^%s+", "")
	text = text:gsub("%s+$", "")
	text = text:gsub("%s+", " ")
	textbox.Text = text
end)

@CharranCZ your code and @Forummer’s first method are working but if I leave my cursor at the same place when I type second space the cursor jumps forward.

https://developer.roblox.com/en-us/api-reference/property/TextBox/CursorPosition

Subtract the current cursor’s position by 1.

I know, but how do I implement this correctly? How do I know when to decrease the CursorPosition, and when not to?

local textbox = script.Parent

textbox:GetPropertyChangedSignal("Text"):Connect(function()
	local text, replacements = textbox.Text, 0
	text = text:gsub("^%s+", "")
	text = text:gsub("%s+$", "")
	text, replacements = text:gsub("%s+", " ")
	if replacements > 0 then
		textbox.CursorPosition -= 1
	end
	textbox.Text = text
end)

gsub()'s second return value indicates how many replacements were made.

1 Like

Now it jumps backwards after the second space…

Then fiddle around with the values until you achieve the desired result.

1 Like

You can use string.len() to see if the space has been cleared or not. If yes then cursor moves 1 backward, if no then nothing. If you use script from Forummer so then you create a new value local textStart. Before you start editing text, you get length of the text with this: textStart = text:len() and under if replacements > 0 then you add this condition:

if textStart ~= text:len() then
	textbox.CursorPosition -= 1
end

Thanks. I think I’ve already tried this, but I’ll try again later.