Replace strings
This article uses Office Scripts to explain how to replace a specific string with another string, and what to watch out for when the replacement doesn’t work as expected, with sample code.
Method to use
Section titled “Method to use”Use the replace method of the String object.
In VBA, you probably used the Replace function with three arguments: the target string, the string to find, and the replacement string. In Office Scripts, you call the method directly on the target string.
/** * @param searchValue The string to replace * @param replaceValue The replacement string */replace(searchValue: string | RegExp, replaceValue: string): string;To delete a specific string, specify an empty string ('') as the second argument.
You can also specify a regular expression as the first argument.
Regular expressionsThis article gives a systematic overview of using regular expressions in Office Scripts, including checking whether strings match, and replacing and splitting strings.
Sample code
Section titled “Sample code”This sample code specifies a target string and stores the replaced result in a separate variable.
function main(workbook: ExcelScript.Workbook) { /** Target string */ const target = 'My favorite fruit is apples';
/** String after replacement */ const replaced = target.replace('apples', 'bananas');
console.log(replaced); // My favorite fruit is bananas}