I’m currently making plugin, and for it to work perfectly, I need to do following things to TextBoxes:
Remove trailing and leading spaces (I know how to do this, but is there a way to combine the pattern?)
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]b → a[1 space]b (remove 1 space as there were 2 spaces) a[1 spaces]b → a[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.
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.
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.
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