Replacing a string from last

Hi,

I was implementing something in my project that required replacing a substring from the last (i.e., the last substring from a string if there is more than one matching substring). I checked the string prototypes to do it easily but couldn't find it. The .replace() method replaces a substring from the beginning. So I decided to propose the .replaceLast() prototype.

I have created a repo with the proposal and looking for a champion to bring it to the committee. I would like to hear more about it if you have any feedback. Also, your suggestion will be appreciated.

Proposal link: GitHub - tajnur007/proposal-string-replace-from-last: Proposal for String.prototype.replaceLast

Mentioning @aclaymore as you would like to know my proposal.

Hi @tajnur007,

Is there a way to show how prevalent this problem is? Maybe looking at uses of existing libraries: replace-last - npm

An alternative API could be adding a 3rd, position parameter to replace similar to String.prototype.includes() - JavaScript | MDN. The index would set the starting point that the search would begin. The caller would still need to do lastIndexOf first, but then wouldn't need to create the substring and concat, so would go from 4 operations to 2.

The replace-last - npm package indicates approximately ~45K downloads in a week. It means that operation is crucial in the JS community.

Your alternative solution (adding a 3rd, position parameter) is good but I hope it will be better if we add a method replaceLast() which is similar to the replace() method. Because we already have a similar naming convention, Array.prototype.find() - JavaScript | MDN and Array.prototype.findLast() - JavaScript | MDN, which do the same operation but in a reverse way.

I understand that adding the position parameter to the replace() method will provide more flexibility in the replacement operation, I appreciate that. We can also keep both, adding the replaceLast() method and adding a 3rd parameter (position) to the replace() method. Expecting other person opinions to make better decisions.

45K/week is not a persuasive number, I'm afraid - for example, p-try - npm which helped to get Promise.try moving has 45 million downloads a week.

Also worth noting that almost all of the download come from envsub - npm which depends on replace-last, and that package is only calling it in one place: envsub/js/DotEnvParser.js at ba23d838431feb41a7f29f47d0ed2525bf5c9276 ยท danday74/envsub ยท GitHub and I think that one place could be replaced with string.slice(0, -1), so it doesn't actually need the package.

1 Like

A while ago there was a suggestion here to add splice to String, which didn't get much positive feedback, but would also allow replace at position -- and IMO that could help other use cases, especially for those scared of regexes -- for example replacing a chunk of text between two found substrings.