Menu
CoddyTech

Replace and Trim

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 3 of 78.

replace(what, with) returns a new string where every appearance of what is replaced with with. Replacing with an empty string removes the text:

var phone := "555-123-4567"
print(phone.replace("-", ""))
print(phone.replace("-", " "))
print(phone)
5551234567
555 123 4567
555-123-4567

The original string does not change. replace() is case-sensitive; replacen() does the same job and ignores case:

var chat := "Hello hello HELLO"
print(chat.replace("hello", "hi"))
print(chat.replacen("hello", "hi"))
Hello hi HELLO
hi hi hi

Text typed by a user often has extra spaces around it. strip_edges() removes spaces, tabs and line breaks from both ends and keeps the ones in the middle:

var typed := "   Ana Lee  "
print("[" + typed.strip_edges() + "]")
[Ana Lee]

strip_edges(true, false) trims only the left end and strip_edges(false, true) only the right end. To remove one specific text at an end, use trim_prefix() or trim_suffix(). They change nothing when the text is not there:

print("level_03.tscn".trim_suffix(".tscn"))
print("level_03.tscn".trim_suffix(".png"))
level_03
level_03.tscn

Each of these methods returns a string, so you can chain them: raw.strip_edges().to_lower().replace(" ", "_").

challenge icon

Challenge

Easy

The program reads a level title into title. Turn it into a slug, a version of the title that can be used as a file name, and print it. In this order:

  1. Remove the spaces at both ends
  2. Convert it to lowercase
  3. Replace every remaining space with -
  4. Remove every !, ? and .

For the input Is Godot Fun? (with spaces around it), the output is:

is-godot-fun

Try it yourself

extends Node

func _ready():
	var title := OS.read_string_from_stdin()
	# Build the slug and print it
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler