Skip to content

Regular expressions

This article gives a systematic overview of using regular expressions in Office Scripts.

To use a regular expression in Office Scripts, either define a regular expression literal enclosed in slashes (/.../) or use a RegExp object.

Both create the same RegExp object, but if you want to use a variable in a regular expression, or build a regular expression dynamically from user input, you need to use the RegExp constructor (new RegExp()).

Sample regular expression definitions
/** Regular expression that matches only two-digit numbers */
const regexp1 = /^[0-9]{2}$/;
/** Regular expression that matches strings starting with "value" */
const regexp2 = new RegExp(`^value.*`);

Check whether a string matches a regular expression

Section titled “Check whether a string matches a regular expression”

If you just want to check whether a string matches a regular expression, use the RegExp.test method.

RegExp.test takes a string as its argument and returns true if it matches the regular expression, or false if it doesn’t.

Checking for a match with the test method
/** Regular expression that matches only two-digit numbers */
const regexp = /^[0-9]{2}$/;
console.log(regexp.test('23')); // true
console.log(regexp.test('2022')); // false

You can also check for a match with the String.search method.

String.search accepts a regular expression as its argument and returns the index of the first match (a position counted from 0). If there’s no match, it returns -1.

Checking for a match with the search method
/** Regular expression that matches if the string contains a two-digit number */
const regexp = /[0-9]{2}/;
console.log('Today is the 17th'.search(regexp)); // 13 (matches from the 14th character)

To replace the parts of a string that match a regular expression with another string, pass a regular expression as an argument to the String.replace method.

Replacing strings with the replace method
/** "value" at the beginning */
const regexp = new RegExp('^value');
const replaced = 'value-content-value'.replace(regexp, 'item'); // item-content-value

Without the g flag, only the first match is replaced.

If you add g to the end of a regular expression literal (/value/g), the entire target string is searched for matches, and every match is replaced. When you use the RegExp constructor, specify the flags as the second argument (new RegExp('value', 'g')).

To split a string at the parts that match a regular expression, pass a regular expression as an argument to the String.split method.

Splitting strings with the split method
/** Regular expression that matches a slash */
const regexp = /\//;
const splitted = '2022/3/17'.split(regexp); // ['2022', '3', '17']