Main Content


Delete substrings within strings



newStr = erase(str,match) deletes all occurrences of match in str. The erase function returns the remaining text as newStr.

If match is an array, then erase deletes every occurrence of every element of match in str. The str and match arguments do not need to be the same size.


collapse all

Create a string array and delete substrings from it. Starting in R2017a, you can create strings using double quotes.

str = ["the quick brown fox jumps";
       "over the lazy dog"]
str = 2x1 string
    "the quick brown fox jumps"
    "over the lazy dog"

If you are using R2016b, create string arrays using the string function instead of double quotes.

Delete the substring "the " from str. The erase function deletes both instances.

newStr = erase(str,"the ")
newStr = 2x1 string
    "quick brown fox jumps"
    "over lazy dog"

Delete multiple substrings from str.

match = ["the ","quick ","lazy "];
newStr = erase(str,match)
newStr = 2x1 string
    "brown fox jumps"
    "over dog"

Since R2020b

Create a string array of file names, including full paths.

str = ["C:\Temp\MyReport.docx";
str = 3x1 string

Delete the paths, leaving only file names. To match paths, create a pattern using the wildcardPattern function that matches all text that includes a final "\" character. Use that pattern with the erase function.

match = wildcardPattern + "\"
match = pattern

    wildcardPattern + "\"

filenames = erase(str,match)
filenames = 3x1 string

For a list of functions that create pattern objects, see pattern.

Create a character vector. Delete the substring, ' World', including the space character.

chr = 'Hello World'
chr = 
'Hello World'
newChr = erase(chr,' World')
newChr = 

Input Arguments

collapse all

Input text, specified as a string array, character vector, or cell array of character vectors.

Text to delete, specified as one of the following:

  • String array

  • Character vector

  • Cell array of character vectors

  • pattern array (since R2020b)


  • To delete multiple occurrences of a match when the occurrences overlap, use the strrep function. erase only deletes the first occurrence when occurrences overlap.

Extended Capabilities

Introduced in R2016b