Stage undefined Draft / January 7, 2025

String.prototype.replaceLast

ECMAScript proposal for String.prototype.replaceLast, i.e. .replaceLast() method on string.

Author: Kazi Tajnur Islam

1 Motivation

Replacing a sub-string in a string is a very common programming pattern. The proposal has a major concerns: Semantical. Which means clearly representing the operation i want. And with the changes. It's may useful in some performance-sensitive scenarios.

ECMAScript currently supports String.prototype.replace to replace the first instance of a sub-string/pattern from a string. However, there is no way to replace the last instance of a substring in a string.

Currently one of the most common way of achieving this is to use a regex:

    function replaceLastSubstring(string, substring, replacement) {
      const regex = new RegExp(`(${substring})(?!.*${substring})`);
      return string.replace(regex, replacement);
    }
  

This approach has the downsides, the regular expression itself can be slightly more complex to understand and debug. Performance might be slightly slower due to the regex engine's overhead. If the substring contains special characters that have meaning within regular expressions (e.g., ., *, +, ?, $, ^, etc.), the regex needs to be properly escaped to avoid unexpected behaviour.

An alternate solution is to combine .lastIndexOf() with .substring():

    function replaceLastSubstring(string, substring, replacement) {
      const lastIndex = string.lastIndexOf(substring);

      if (lastIndex !== -1) {
        const firstPart = string.substring(0, lastIndex);
        const lastPart = string.substring(lastIndex + substring.length);
        return firstPart + replacement + lastPart;
      }

      return string;
    }
  

The code involves string manipulation (concatenation and substring extraction), which can be less concise than using a single replaceLast() method.

Example usage:

    const testString = 'aabca';
    const replacedString = replaceLastSubstring(testString, 'a', '_');
    console.log(replacedString);

    // Output: aabc_
  

2 Proposed solution

I propose the addition of a new method to the String prototype - replaceLast. This would give developers a straight-forward way to accomplish this common, basic operation.

    const testString = 'aabca';
    const replacedString = testString.replaceLast('a', '_');
  

This would behave the same as String.prototype.replace but would iterate from the last to the first.

3 High-level API

The proposed signature is the same as the existing String.prototype.replace method:

    String.prototype.replaceLast(searchValue, replaceValue)
  

4 FAQ

What are the main benefits?

A simplified API for this common use-case that does not require RegExp knowledge. Possibly improved optimization potential on the VM side.

What about adding a direction parameter to the replace instead?

I thought about this way first, i.e. String.prototype.replace(searchValue, replaceValue, fromLast) - the default value of the fromLast will be false. This can be an awkward interface because ECMAScript already have similar interface like replaceLast, e.g. Array.prototype.findLast, which clearly defines it's operation by the name.

A Copyright & Software License

Copyright Notice

© 2025 Kazi Tajnur Islam

Software License

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.