const replaceLast = (str: string, pattern: RegExp, replacement: string) => {
        const match: string =
          typeof pattern === 'string'
            ? pattern
            : (str.match(new RegExp(pattern.source, 'g')) || []).slice(-1)[0];
        if (!match) return str;
        const last: number = str.lastIndexOf(match);
        return last !== -1
          ? `${str.slice(0, last)}${replacement}${str.slice(last + match.length)}`
          : str;
      };
      
      Typescript language logo

      Replace last occurrence

      Codiga's TypeScript Recipes

      Replaces the last occurrence of a pattern in a string.

      0 Comments

        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.