replaceAllAsync

import { replaceAllAsync } from "jsr:@ende/regexp/unstable-replace-all-async";

function ยท experimental

async function replaceAllAsync(text: string, searchValue: RegExp | string, replacer: (substring: string, ...args: any[]) => Promise<string> | string): Promise<string>

Asynchronously replaces all occurrences of a pattern in a string.

text: string

The original string.

searchValue: RegExp | string

The regular expression pattern to search for.

replacer: (substring: string, ...args: any[]) => Promise<string> | string

An asynchronous function that returns the replacement string.

Returns

A promise that resolves to the modified string.

Example: Usage

import { replaceAllAsync } from "@ende/regexp/unstable-replace-all-async";
import { assertEquals } from "@ende/assert";

const result = await replaceAllAsync(
  "https://example.com/ and https://example.com/not-found!",
  /https:\/\/([\w\-/.]+)/g,
  async (match, address) => {
    const { status } = await fetch(match, { method: "HEAD" });
    return `${address} returned status ${status}`;
  },
);

assertEquals(
  result,
  "example.com/ returned status 200 and example.com/not-found returned status 404!",
);

Source