In Godot, string functions are methods on the GDScript String type, used to search, split, clean, format, validate, and convert text. For example, var clean = user_input.strip_edges().to_lower() removes leading and trailing whitespace and then lowercases the result; most string methods return a new value, so assign that value if you want to keep it.
What a String is in Godot
A String holds text such as a label, a file path, dialogue, or player-entered input. In GDScript, you can create one with a quoted literal or receive one from a function, a node property, or a conversion. Godot 4 uses the same basic string methods across typical GDScript projects, though a project using an older Godot release may have differences in available APIs.
String methods are called with dot notation. For instance, text.to_upper() returns an uppercase version, while text.is_empty() reports whether the value contains no characters. A key distinction is that calling a method does not generally alter the original variable in place. To retain a transformed value, write an assignment such as text = text.strip_edges().
Many methods can be chained, but intermediate variables can make a transformation easier to read and debug. They are also useful when the same cleaned value is needed more than once.
Changing case and trimming whitespace
For straightforward cleanup, Godot provides case-conversion and trimming methods. to_lower() and to_upper() change letter case, and capitalize() applies capitalization according to the method’s rules. For example:
var label = ' welcome, pilot '
var display_label = label.strip_edges().capitalize()
Here, display_label is Welcome, pilot; label still contains the original spaces and lowercase text. strip_edges() removes whitespace at the beginning and end, not spaces between words. If only one side needs trimming, use strip_edges() with its optional arguments or the more specific lstrip() and rstrip() methods when appropriate.
Case conversion is useful for normalizing comparisons, but it is not always suitable for presentation. A display name may need to preserve the spelling a player chose, while a command keyword can be normalized before comparison. Also, lowercase conversion alone is not a universal solution for every language’s case-folding rules; for ordinary game commands and identifiers it is often sufficient, but language-sensitive matching needs more deliberate handling.
Searching, checking, and replacing text
Use contains() to check whether a string includes a smaller string. begins_with() and ends_with() test its boundaries. These checks are case-sensitive, so 'Godot'.contains('god') does not match. If your input should be treated without regard to case, normalize both sides before comparing.
To locate text, find() returns the position of a match, or -1 if none is found. rfind() searches from the end. For example:
var filename = 'level.final.tscn'
var dot_position = filename.rfind('.')
if dot_position != -1:
print(filename.substr(dot_position + 1))
This prints tscn. Checking for -1 matters: a missing match is not the same as a match at position zero. Use count() when you need the number of occurrences of a substring.
replace(old, new) replaces occurrences of one string with another, while replacen(old, new) performs case-insensitive replacement. For example, 'red RED'.replacen('red', 'blue') produces blue blue. These methods are useful for simple literal substitutions; they do not interpret the search text as a regular expression. For patterns such as variable-width numbers or optional groups, use Godot’s RegEx class instead.
Splitting strings and joining them again
split() breaks a string into parts using a delimiter and returns a PackedStringArray. This is useful for simple data formats, command input, or lists separated by a known character:
var line = 'Mira,12,active'
var fields = line.split(',')
var player_name = fields[0]
var level = fields[1].to_int()
This example assumes the input really has at least three comma-separated fields. Production code should check the array’s size before reading an index, because malformed or incomplete input can otherwise cause an error. Splitting on commas is not enough to parse every CSV file: quoted fields can contain commas and escaping rules add complexity. Use a CSV-aware parser for general CSV data.
The optional arguments to split() let you control whether empty parts are kept and how many splits occur. Keeping empty parts can be important: splitting 'a,,c' and discarding empty pieces changes the field positions. Check the method’s defaults and choose explicitly when the distinction matters.
To combine string parts, call join() on the separator:
var tags = PackedStringArray(['quest', 'daily', 'easy'])
var summary = ' | '.join(tags)
The resulting value is quest | daily | easy. Joining is often clearer than repeatedly concatenating inside a loop, especially when assembling a line from many pieces. If you need numeric values in the array, convert them to strings first or build the output using an appropriate formatting method.
Formatting strings for messages and UI
String formatting keeps text templates separate from the values inserted into them. In GDScript, the % operator supports format placeholders such as %s for text and %d for an integer:
var player_name = 'Mira'
var score = 120
var message = '%s scored %d points' % [player_name, score]
For named values, format() can use a dictionary and placeholders in braces:
var message = 'Hello, {name}!'.format({'name': player_name})
Named placeholders can be easier to maintain when a message contains several values, because the mapping is visible in the dictionary. Formatting is not the same as localization, however. A translated sentence may change word order or grammar, so avoid building multilingual UI by concatenating fragments that assume one language’s sentence structure. Use Godot’s translation workflow for localized text.
For a small fixed message, concatenation with + is valid, but repeated concatenation can become hard to read and can cause unnecessary intermediate values. Prefer a clear format template or gather parts and join them when the message is assembled from a collection.
Validating and converting text
Text received from a player, a save file, or a network message should be checked before it is treated as a number or identifier. String methods including is_valid_int() and is_valid_float() can test whether text has an acceptable numeric form. Then use to_int() or to_float() to convert it:
var input = '42'
if input.is_valid_int():
var amount = input.to_int()
This separates validation from conversion. In particular, do not rely on conversion alone to tell you whether the original input was valid: conversion methods can return a default value for text that does not represent a valid number, making invalid input easy to confuse with a real zero. You may also need application-specific checks, such as whether a number is within an allowed range.
Other useful checks include is_empty() for an empty string and is_valid_identifier() for identifier-shaped text. A syntactically valid identifier is not automatically safe or appropriate as a node name, filename, or user account name; validate according to the actual use. For example, a filename needs rules about path separators and reserved names that a variable identifier check does not provide.
Unicode, indexing, and user-visible characters
Godot strings support Unicode, so they can contain text beyond basic English letters. Still, a user-perceived character is not always represented by one simple code point. Accented letters may be stored as a precomposed character or as a base letter followed by a combining mark, and emoji can be made from multiple code points joined together. As a result, indexing or counting string positions may not correspond exactly to what a person sees as one symbol.
This matters when truncating names, placing a cursor, measuring a character limit, or slicing text for display. A simple substr() is appropriate for many technical strings and known-format tokens, but it may split a multi-code-point grapheme in an undesirable place. If the goal is a visual character limit, test with the scripts and emoji your project supports rather than assuming that a string index equals a displayed character count.
Similarly, byte length and character length are different concepts. UTF-8 encoding can use multiple bytes for a character. When converting text to bytes for a file or network protocol, follow that format’s encoding rules rather than using character positions as byte offsets.
StringName, paths, and regular expressions
StringName is a separate Godot type intended for names that are compared or reused frequently, such as method names, input actions, and property identifiers. In Godot 4, the &'name' literal creates a StringName. It is not a general replacement for String: use ordinary strings for changing user text, dialogue, or large amounts of unique content. Convert deliberately when an API expects one type rather than assuming every string-like value is interchangeable.
Paths deserve care because a path is text with platform and resource-system rules. Godot offers path-related string methods such as path_join() for joining path components; use it rather than casually adding separators when building paths. Resource paths such as res:// and user data paths such as user:// have Godot-specific meanings, so they are not interchangeable with arbitrary operating-system paths.
For advanced search and substitution, Godot’s RegEx class handles pattern matching that ordinary find() and replace() do not. A regular expression is more powerful, but also more complex: special characters have pattern meanings, and patterns should be tested against empty, malformed, and unexpected inputs. Prefer literal string methods for literal searches because they are easier to read and less likely to behave unexpectedly.
Common mistakes to avoid
- Forgetting to save the return value: write
text = text.strip_edges()if the cleaned version should replace the variable. - Assuming a search always succeeds: test the result of
find()against-1before using it as a position. - Splitting a complex format by hand: delimiters inside quoted fields make a naive split unsuitable for full CSV parsing.
- Using a string check as complete security validation: validate according to the destination, especially for paths, commands, and network data.
- Confusing case conversion with localization: uppercasing or lowercasing does not translate text or guarantee language-aware comparisons.
When a string expression behaves unexpectedly, inspect the value and its type at the point of use. A value that looks like text in the editor may instead be a StringName, a number, or a nullable result from another API. Clear conversions and small intermediate variables make these mismatches easier to find.
Frequently Asked Questions
How do I make a string lowercase in Godot?
Call to_lower(), for example var normalized = text.to_lower(). Assign the returned value if you want to keep it; the original variable is not changed just by calling the method.
How do I check whether a string contains text?
Use contains(), such as text.contains('key'). It is case-sensitive. For a case-insensitive check, normalize the value and search term consistently before calling it.
How do I split a string in GDScript?
Call split(delimiter), which returns a PackedStringArray. Check the result’s size before indexing it, and do not use a basic delimiter split as a complete parser for formats with quoting or escaping.
What is the difference between String and StringName?String is the normal choice for text that may vary or be shown to a user. StringName is designed for reusable names such as identifiers and is commonly used by Godot APIs for that purpose.
Does Godot change a string when I call replace()?
No. replace() returns a string containing the replacement. To retain it, assign the result, for example text = text.replace('old', 'new').
Related
- Snowflake SPLIT_PART: Syntax, Examples, and Common Issues
- JavaScript split() Explained: Strings, Limits, and Examples
- Microsoft Access Split Form: How It Works and When to Use It
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Insert a Horizontal Page Break in Excel the Right WayTo insert a horizontal page break in Excel for Microsoft 365 on Windows, select the row directly below…
- Excel Convert Text to Dates: Methods, Formulas, and FixesTo convert dates stored as text in Excel, select the cells and use Data > Text to Columns,…
- Excel Table Array Lookup: Using VLOOKUP in a TableAn Excel table array lookup usually means using the table_array argument in VLOOKUP: it tells Excel which range…
- VLOOKUP Examples for Multiple Sheets in ExcelTo look up a value on another worksheet, use VLOOKUP with that sheet’s range, such as =VLOOKUP(A2,Products!$A$2:$C$100,2,FALSE). To…
- Excel Formula List: Basic Functions, Uses, and ExamplesA basic Excel formula list includes SUM for totals, AVERAGE for means, COUNT and COUNTA for counting, MIN…
- Date Filter Formula in Excel: Examples and TipsIn Excel for Microsoft 365, use the FILTER function to return rows whose dates meet your criteria. For…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.