String.replaceFirst
func String.replaceFirst(s: string, old: string, new: string): stringString.replaceFirst returns s with the first occurrence of old replaced by new. It panics if old is empty.
Details
- When
olddoes not occur, the result equalss. - Matching is exact, code point by code point, with no case folding or normalization.
- To replace every occurrence, use
String.replace.
Basic examples
Replace the first - and keep the rest:
String.replaceFirst("a-b-c", "-", "+") // "a+b-c"When old does not occur, the string comes back unchanged:
String.replaceFirst("abc", "x", "y") // "abc"An empty new removes the first occurrence:
String.replaceFirst("2026-11-08", "-", "") // "202611-08"Scope
old can be any string that is not empty, new can be any string, and new may contain old:
String.replaceFirst("a::b::c", "::", "/") // "a/b::c"
String.replaceFirst("aXa", "a", "aa") // "aaXa"The first occurrence is the leftmost one, so the match starts at the first position where old begins:
String.replaceFirst("aaa", "aa", "b") // "ba"In the empty string, old never occurs, so the result is "":
String.replaceFirst("", "x", "y") // ""The whole string can be old:
String.replaceFirst("abc", "abc", "xyz") // "xyz"Unicode text works like any other. The match is exact, so case matters and a precomposed é does not contain the code point e:
String.replaceFirst("🐜🐝🐜", "🐜", "🐞") // "🐞🐝🐜"
String.replaceFirst("Café", "c", "K") // "Café"
String.replaceFirst("é", "e", "a") // "é"The search matches code points, not graphemes, so it can strip the first combining accent from its letter. The code point 769 is the accent U+0301 that stays on t:
let s = String.replaceFirst("e\u{301}t\u{301}", "\u{301}", "")
s.toCodePoints() // [101, 116, 769]Call it through ., in a pipe, or with named arguments:
"x.y.z".replaceFirst(".", "!") // "x!y.z"
"x.y.z" | String.replaceFirst(".", "!") // "x!y.z"
String.replaceFirst(s: "a b c", old: " ", new: "_") // "a_b c"Applications
Fill ? placeholders in order, one value each:
func fill(template: string, values: Array[string]): string {
var out = template
for v in values {
out = out.replaceFirst("?", v)
}
out
}
println(fill("? + ? = ?", ["1", "2", "3"]))1 + 2 = 3Turn only the first _ of a snake_case name into a space; later underscores stay:
let names = ["first_name", "zip_code_ext", "id"]
for name in names {
println(name.replaceFirst("_", " "))
}first name
zip code_ext
idMark the first # in a document, in a pipe:
let doc = "# Intro\ntext\n# Usage\n"
let marked = doc | String.replaceFirst("# ", "# [start] ")
print(marked)# [start] Intro
text
# UsageProperties and relations
When old occurs, the result is the text before it, then new, then the text after it, as String.cut splits it:
let s = "user=ann=admin"
let c = s.cut("=")
assert(c != null)
assert(s.replaceFirst("=", ": ") == c.before + ": " + c.after)When old does not occur, the result is s:
let s = "plain"
assert(!s.contains("="))
assert(s.replaceFirst("=", ": ") == s)The length changes by the difference between new and old when old occurs, and does not change otherwise:
let s = "a-b-c"
let r = s.replaceFirst("-", "--")
assert(r.length() == s.length() - 1 + 2)When old occurs at most once, String.replaceFirst and String.replace agree:
for s in ["k=v", "kv", "=", ""] {
assert(s.count("=") <= 1)
assert(s.replaceFirst("=", ":") == s.replace("=", ":"))
}Possible issues
An empty old panics:
String.replaceFirst("abc", "", "x") // panic: String.replaceFirst needs an old string that is not emptyString.replaceFirst returns a new string. Calling it without using the result changes nothing:
var s = "a-b"
s.replaceFirst("-", "+")
println(s)
s = s.replaceFirst("-", "+")
println(s)a-b
a+bold is plain text, not a pattern: . matches a dot only. To replace the first match of a regular expression, use Regex.replaceFirst:
String.replaceFirst("a1b22", "[0-9]+", "#") // "a1b22"String.replaceFirst matches anywhere, not only at the start:
String.replaceFirst("C# # notes", "# ", "## ") // "C## # notes"To change only a leading prefix, test it with String.startsWith first:
func promote(s: string): string {
if s.startsWith("# ") { "#" + s } else { s }
}
println(promote("C# # notes"))
println(promote("# x"))C# # notes
## xEach call searches the whole string again from the front, including text that an earlier call inserted. In the fill helper above, a value that contains ? is itself replaced by the next value:
fill("? ?", ["?", "x"]) // "x ?"A loop that replaces until old is gone never ends when new contains old. To replace every occurrence, use String.replace.
There is no String.replaceLast. To replace the last occurrence, find it with String.lastIndexOf and rebuild the string around it:
func replaceLast(s: string, old: string, new: string): string {
let i = s.lastIndexOf(old) ?? return s
s.slice(0, i) + new + s.slice(i + old.length(), s.length())
}
println(replaceLast("a-b-c", "-", "+"))a-b+cSee also
String.replace · Regex.replaceFirst · String.cut · String.indexOf · String.lastIndexOf · String.trimPrefix · String.count · String.contains
