I want to remove all occurrences of substring = .
in a string except the last one.
E.G:
1.2.3.4
should become:
A replaceAllButLast
function is more useful than a removeAllButLast
function. When you want to remove just replace with an empty string:
function replaceAllButLast(str, pOld, pNew) {
var parts = str.split(pOld)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var test = 'hello there hello there hello there'
test = replaceAllButLast(test, ' there', '')
console.log(test) // hello hello hello there