Javascript replace last occurence of text in a string

Posted by Ruth on Stack Overflow See other posts from Stack Overflow or by Ruth
Published on 2010-04-28T13:09:31Z Indexed on 2010/04/28 13:13 UTC
Read the original article Hit count: 425

Filed under:
|
|

Hi all

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], 'finsih')
     }
 }

I want to replace the last occurence 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 occurence of it. Does anyone know how I can amend that snippet so that it only replaces the last instance of 'one'

Thank you Ruth

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about string