Ruth
Ruth

Reputation: 5816

JavaScript: replace last occurrence of text in a string

See my code snippet below:

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         str = str.replace(list[i], 'finish')
     }
 }

I want to replace the last occurrence of the word one with the word finish in the string, what I have will not work because the replace method will only replace the first occurrence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'

Upvotes: 154

Views: 221551

Answers (15)

Irving
Irving

Reputation: 1267

Thought I'd answer here since this came up first in my Google search and there's no answer (outside of Matt's creative answer :)) that generically replaces the last occurrence of a string of characters when the text to replace might not be at the end of the string.

if (!String.prototype.replaceLast) {
    String.prototype.replaceLast = function(find, replace) {
        var index = this.lastIndexOf(find);

        if (index >= 0) {
            return this.substring(0, index) + replace + this.substring(index + find.length);
        }
    
        return this.toString();
    };
}

var str = 'one two, one three, one four, one';

// outputs: one two, one three, one four, finish
console.log(str.replaceLast('one', 'finish'));

// outputs: one two, one three, one four; one
console.log(str.replaceLast(',', ';'));

Upvotes: 12

Tim Long
Tim Long

Reputation: 2149

A simple one-liner answer without any regex would be:

str = str.substring(0, str.lastIndexOf(list[i])) + 'finish'

Upvotes: 16

pguardiario
pguardiario

Reputation: 55002

A negative lookahead solution:

str.replace(/(one)(?!.*\1)/, 'finish')

An explanation provided by the site regex101.com,

/(one)(?!.*\1)/

1st Capturing Group (one)

  • one - matches the characters one literally (case sensitive)

Negative Lookahead (?!.*\1)

Assert that the Regex below does not match

  • . matches any character (except for line terminators)
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • \1 matches the same text as most recently matched by the 1st capturing group

Upvotes: 12

user20442474
user20442474

Reputation: 1

if (string.search(searchstring)>-1) {
    stringnew=((text.split("").reverse().join("")).replace(searchstring, 
    subststring).split("").reverse().join(""))
    }

//with var string= "sdgu()ert(dhfj ) he ) gfrt"
//var searchstring="f"
//var subststring="X"
//var stringnew=""
//results in
//string    :  sdgu()ert(dhfj ) he ) gfrt
//stringnew :  sdgu()ert(dhfj ) he ) gXrt

Upvotes: 0

Muhamet Rexhepi
Muhamet Rexhepi

Reputation: 21

function replaceLast(text, searchValue, replaceValue) {
  const lastOccurrenceIndex = text.lastIndexOf(searchValue)
  return `${
      text.slice(0, lastOccurrenceIndex)
    }${
      replaceValue
    }${
      text.slice(lastOccurrenceIndex + searchValue.length)
    }`
}

Upvotes: 2

Pepijn Olivier
Pepijn Olivier

Reputation: 976

I did not like any of the answers above and came up with the below

function isString(variable) { 
    return typeof (variable) === 'string'; 
}

function replaceLastOccurrenceInString(input, find, replaceWith) {
    if (!isString(input) || !isString(find) || !isString(replaceWith)) {
        // returns input on invalid arguments
        return input;
    }

    const lastIndex = input.lastIndexOf(find);
    if (lastIndex < 0) {
        return input;
    }

    return input.substr(0, lastIndex) + replaceWith + input.substr(lastIndex + find.length);
}

Usage:

const input = 'ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty';
const find = 'teen';
const replaceWith = 'teenhundred';

const output = replaceLastOccurrenceInString(input, find, replaceWith);
console.log(output);

// output: ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteenhundred twenty

Hope that helps!

Upvotes: 8

Hexer338
Hexer338

Reputation: 41

Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

str = str.substring(0, str.length - list[i].length) + "finish"

Upvotes: 3

Pascut
Pascut

Reputation: 3434

If speed is important, use this:

/**
 * Replace last occurrence of a string with another string
 * x - the initial string
 * y - string to replace
 * z - string that will replace
 */
function replaceLast(x, y, z){
    var a = x.split("");
    var length = y.length;
    if(x.lastIndexOf(y) != -1) {
        for(var i = x.lastIndexOf(y); i < x.lastIndexOf(y) + length; i++) {
            if(i == x.lastIndexOf(y)) {
                a[i] = z;
            }
            else {
                delete a[i];
            }
        }
    }

    return a.join("");
}

It's faster than using RegExp.

Upvotes: 3

mr.freeze
mr.freeze

Reputation: 14050

Here's a method that only uses splitting and joining. It's a little more readable so thought it was worth sharing:

    String.prototype.replaceLast = function (what, replacement) {
        var pcs = this.split(what);
        var lastPc = pcs.pop();
        return pcs.join(what) + replacement + lastPc;
    };

Upvotes: 16

zaxvox
zaxvox

Reputation: 9

str = (str + '?').replace(list[i] + '?', 'finish');

Upvotes: -1

Fusty
Fusty

Reputation: 376

Couldn't you just reverse the string and replace only the first occurrence of the reversed search pattern? I'm thinking . . .

var list = ['one', 'two', 'three', 'four'];
var str = 'one two, one three, one four, one';
for ( var i = 0; i < list.length; i++)
{
     if (str.endsWith(list[i])
     {
         var reversedHaystack = str.split('').reverse().join('');
         var reversedNeedle = list[i].split('').reverse().join('');

         reversedHaystack = reversedHaystack.replace(reversedNeedle, 'hsinif');
         str = reversedHaystack.split('').reverse().join('');
     }
 }

Upvotes: 3

dario nascimento
dario nascimento

Reputation: 597

Old fashioned and big code but efficient as possible:

function replaceLast(origin,text){
    textLenght = text.length;
    originLen = origin.length
    if(textLenght == 0)
        return origin;

    start = originLen-textLenght;
    if(start < 0){
        return origin;
    }
    if(start == 0){
        return "";
    }
    for(i = start; i >= 0; i--){
        k = 0;
        while(origin[i+k] == text[k]){
            k++
            if(k == textLenght)
                break;
        }
        if(k == textLenght)
            break;
    }
    //not founded
    if(k != textLenght)
        return origin;

    //founded and i starts on correct and i+k is the first char after
    end = origin.substring(i+k,originLen);
    if(i == 0)
        return end;
    else{
        start = origin.substring(0,i) 
        return (start + end);
    }
}

Upvotes: 0

WilsonCPU
WilsonCPU

Reputation: 161

Not as elegant as the regex answers above, but easier to follow for the not-as-savvy among us:

function removeLastInstance(badtext, str) {
    var charpos = str.lastIndexOf(badtext);
    if (charpos<0) return str;
    ptone = str.substring(0,charpos);
    pttwo = str.substring(charpos+(badtext.length));
    return (ptone+pttwo);
}

I realize this is likely slower and more wasteful than the regex examples, but I think it might be helpful as an illustration of how string manipulations can be done. (It can also be condensed a bit, but again, I wanted each step to be clear.)

Upvotes: 16

T.J. Crowder
T.J. Crowder

Reputation: 1075149

You can use String#lastIndexOf to find the last occurrence of the word, and then String#substring and concatenation to build the replacement string.

n = str.lastIndexOf(list[i]);
if (n >= 0 && n + list[i].length >= str.length) {
    str = str.substring(0, n) + "finish";
}

...or along those lines.

Upvotes: 52

Pointy
Pointy

Reputation: 413856

Well, if the string really ends with the pattern, you could do this:

str = str.replace(new RegExp(list[i] + '$'), 'finish');

Upvotes: 173

Related Questions