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.
Method to use
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.
/**
* @param searchValue Character string to be replaced
* @param replaceValue Replaced character string
*/
replace(searchValue: string | RegExp, replaceValue: string): string;
It is important to note that the execution of this method will not change the original string.
The return value of this method is returned as a return value.
let target = 'I ate bread for breakfast';
let replaced = target.replace('bread', 'cooked rice');
console.log(target); // I ate bread for breakfast
console.log(replaced); // I ate rice for breakfast
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.
📄️ Formal performance
This section describes the systematic use of regular expressions in Office scripts, such as matching the character string using regular expressions and replacing and splitting the character string.
Sample code
This is a sample code that specifies the target character string and stores replacement results in another variable.
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
}