replace

Replaces occurrences of a substring or pattern.

Category: Language Fundamentals > Data Types

Syntax

newStr = replace(str, old, new)

Replaces every old in str by new.

Description

Matching is literal and case-sensitive, and applies to every element of str. When old and new are arrays, the pairs are applied together in a single pass, so one replacement cannot be re-replaced by another. For rules based on regular expressions, use regexprep.

Input arguments

str
String array, character vector or cell array of character vectors.
old
Text to find, or an array of texts, or a pattern.
new
Replacement text, or an array with one replacement per entry of old.

Output arguments

newStr
Same type as str.

Example

replace("hello world", "world", "there")
replace(["aa","ba"], "a", "x")
replace("abc", ["a","b"], ["1","2"])
Output
ans = "hello there"
ans = 1×2 string array

    "xx"    "bx"
ans = "12c"

See also

strrep regexprep replaceBetween extractBefore erase