Skip to content

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.

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.

Details of the replace method
/**
* @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.

This sample code specifies a target string and stores the replaced result in a separate variable.

Sample of replacing a string
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
}