🔄 Returns a new string with matches of a pattern replaced by a replacement.

Syntax

TypeScript
import { stringReplace } from '@opentf/std';

stringReplace(
  str: string,
  pattern: string | RegExp,
  replacement: string | ((...args: any[]) => string),
  options?: {
    all?: boolean;
    case?: boolean;
  }
): string;

Parameters

  • str: The source string.

  • pattern: The string or regular expression to match.

  • replacement: The replacement string or a function to be called for each match.

  • options:

    • all: If true, replaces all occurrences (like g flag). Default: false.

    • case: If true, performs case-insensitive matching (like i flag). Default: false.

Returns

A new string with the replacements made.

String patterns are treated literally. Regular expression patterns preserve their existing flags, and the all / case options add g / i behavior on top.

Examples

TypeScript
stringReplace('abc', 'a', 'x') //=> 'xbc'

stringReplace('abbc', 'b', '', { all: true }) //=> 'ac'

stringReplace('aBbBc', 'B', '', { all: true, case: true }) //=> 'ac'

const paragraph = "I think Ruth's dog is cuter than your dog!";
stringReplace(paragraph, /dog/, 'ferret') //=> "I think Ruth's ferret is cuter than your dog!"

// Using a function as replacement
function fahrenheitToCelsius(match, p1) {
  return `${((p1 - 32) * 5) / 9}C`;
}
stringReplace('212F', /(-?\d+(?:\.\d*)?)F\b/, fahrenheitToCelsius) //=> '100C'
Last updated on
Edit this page