If the first character of a string is a new line, how do I remove that specific character using a script?

I am using a external endpoint to generate some strings.
However, there is a bug where sometimes the string that the endpoint generates starts on a new line.

[[This is what I want]]

[[This is what I want.
The string doesn't start as a new line, which is okay.]]

[[
This is not what I want. The string starts on a new line.]] --endpoint sometimes returns this

How would I check to see if the first character is a new line? And how would I then remove that character?

--I have tried doing this (which works), but it applied to all the new lines.
local newText = string.gsub(text, "%s+", " ")

You can use the ‘^’ character to check occurrences only at the beginning of a string. We can combine that with the newline escape sequence, so we get rid of only the newline character at the beginning of the string.
Here’s a good page from Roblox I found that covers strings and string patterns if you would like to learn more: Strings | Roblox Creator Documentation

local text = [[
Get rid of the new line!]]

local newText = string.gsub(text, "^\n", "")

print(text) --
            --Get rid of the new line!

print(newText) --Get rid of the new line!

Oddly, though, that string you provided doesn’t seem to actually contain a new line? That might be just a quirk with how I input it.

1 Like

Per Lua documentation:

For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string.

Your solution will work just fine. You can also try this text:

local text = "\nGet rid of the new line!"

Yea the string I provided was only to clarify what I meant in case my explanation was confusing.

How about this. Think of it like when you put a new line in a text label (ignore the multiline property).