Replace last occurrence

    0

    0

    Giovanny Gongora

    Codiga's TypeScript Recipes

    Replaces the last occurrence of a pattern in a string.

    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;
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.