Replace Last Occurrence in String

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the replaceLast function in JavaScript, which replaces the last occurrence of a pattern in a given string with a specified replacement. This lab will guide you through the implementation of the replaceLast function, which will enable you to manipulate strings in a more efficient and flexible manner. By the end of this lab, you will have a solid understanding of how to replace the last occurrence of a pattern in a string and will be able to apply this knowledge to your future programming projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28594{{"`Replace Last Occurrence in String`"}} javascript/data_types -.-> lab-28594{{"`Replace Last Occurrence in String`"}} javascript/arith_ops -.-> lab-28594{{"`Replace Last Occurrence in String`"}} javascript/comp_ops -.-> lab-28594{{"`Replace Last Occurrence in String`"}} javascript/cond_stmts -.-> lab-28594{{"`Replace Last Occurrence in String`"}} javascript/template_lit -.-> lab-28594{{"`Replace Last Occurrence in String`"}} end

Function to Replace the Last Occurrence of a Pattern in a String

Here is a function that replaces the last occurrence of a pattern in a string:

const replaceLast = (str, pattern, replacement) => {

To use it, open the Terminal/SSH and type node.

  • First, use typeof to determine if pattern is a string or a regular expression.
  • If the pattern is a string, use it as the match.
  • Otherwise, use the RegExp constructor to create a new regular expression using the RegExp.prototype.source of the pattern and adding the 'g' flag to it. Use String.prototype.match() and Array.prototype.slice() to get the last match, if any.
const match =
  typeof pattern === "string"
    ? pattern
    : (str.match(new RegExp(pattern.source, "g")) || []).slice(-1)[0];
  • Use String.prototype.lastIndexOf() to find the last occurrence of the match in the string.
  • If a match is found, use String.prototype.slice() and a template literal to replace the matching substring with the given replacement.
  • If no match is found, return the original string.
  if (!match) return str;
  const last = str.lastIndexOf(match);
  return last !== -1
    ? `${str.slice(0, last)}${replacement}${str.slice(last + match.length)}`
    : str;
};

Here are some examples of how to use the function:

replaceLast("abcabdef", "ab", "gg"); // 'abcggdef'
replaceLast("abcabdef", /ab/, "gg"); // 'abcggdef'
replaceLast("abcabdef", "ad", "gg"); // 'abcabdef'
replaceLast("abcabdef", /ad/, "gg"); // 'abcabdef'

Summary

Congratulations! You have completed the Replace Last Occurrence in String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like