Skip to content

Replacement of string

This time, I will explain how to replace a specific string with another character string using an office script, and the points to note when it cannot be replaced well.

Use the replace method included in the String object.

I think that VBA used the Replace function to specify the target character string, the character string to be replaced, the replacement string, and three arguments.Execute the method.

Details of replace method
/**
* @param searchValue Character string to be replaced
* @param replaceValue Replaced character string
*/
replace(searchValue: string | RegExp, replaceValue: string): string;

If you want to delete a specific string, specify a blank ('') as the second argument.

You can also specify a regular expression in the first argument.

This is a sample code that specifies the target character string and stores replacement results in another variable.

Sample of replacement of string
function main(workbook: ExcelScript.Workbook) {
/** Target character string */
const target = 'My favorite fruit is Apple';
/** Substitution string */
const replaced = target.replace('Apple', 'Banana');
console.log(replaced); // My favorite fruit is Banana
}