String
strReplace

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

Syntax

import { strReplace } from '@opentf/std';
 
strReplace(
  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.

Examples

strReplace('abc', 'a', 'x') //=> 'xbc'
 
strReplace('abbc', 'b', '', { all: true }) //=> 'ac'
 
strReplace('aBbBc', 'B', '', { all: true, case: true }) //=> 'ac'
 
const paragraph = "I think Ruth's dog is cuter than your dog!";
strReplace(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`;
}
strReplace('212F', /(-?\d+(?:\.\d*)?)F\b/, fahrenheitToCelsius) //=> '100C'

Related

Try