.replaceFirst(old,new)
Description
replaceFirst substitutes only the first occurrence of a substring with a new substring within a string. Unlike .replace() which replaces all occurrences, this method only changes the first match.
Parameters
replaceFirst needs two parameters:
old: the substring to search for
new: the substring to replace it with
Usage On Strings
str = "hello hello world"
log str.replaceFirst("hello", "hi")
// "hi hello world"
// only the first "hello" is replaced
str = "one two one two"
log str.replaceFirst("one", "1")
// "1 two one two"
// subsequent matches remain unchanged
str = "aaa"
log str.replaceFirst("a", "b")
// "baa"
// only first character is replaced
str = "no matches here"
log str.replaceFirst("xyz", "abc")
// "no matches here"
// if the old substring isn't found, the original string is returned unchanged
Last updated
Was this helpful?