I want to remove all occurrences of substring = .
in a string except the last one.
E.G:
1.2.3.4
should become:
You can do something like this:
var str = '1.2.3.4';
var last = str.lastIndexOf('.');
var butLast = str.substring(0, last).replace(/\./g, '');
var res = butLast + str.substring(last);
Live example:
You could reverse the string, remove all occurrences of substring except the first, and reverse it again to get what you want.
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