JavaScript: replace last occurrence of text in a string -
see code snippet below:
var list = ['one', 'two', 'three', 'four']; var str = 'one two, 1 three, 1 four, one'; ( var = 0; < list.length; i++) { if (str.endswith(list[i]) { str = str.replace(list[i], 'finish') } }
i want replace last occurrence of word 1 word finish in string, have not work because replace method replace first occurrence of it. know how can amend snippet replaces last instance of 'one'
well, if string ends pattern, this:
str = str.replace(new regexp(list[i] + '$'), 'finish');
Comments
Post a Comment