Reputation: 1036
I want to replace multiple occurrence of a specific word in a string and keep only the last one.
"How about a how about b how about c" to ==>
"a b How about c"
I use string.replace to replace all occurence,yet I still want the last one.sorry if it's naive
Upvotes: 0
Views: 407
Reputation: 35995
A slightly different approach, supports both RegExp and normal string needles:
var replaceAllBarLast = function(str, needle, replacement){
var out = '', last = { i:0, m: null }, res = -1;
/// RegExp support
if ( needle.exec ) {
if ( !needle.global ) throw new Error('RegExp must be global');
while( (res = needle.exec(str)) !== null ) {
( last.m ) && ( last.i += res[0].length, out += replacement );
out += str.substring( last.i, res.index );
last.i = res.index;
last.m = res[0];
}
}
/// Normal string support -- case sensitive
else {
while( (res = str.indexOf( needle, res+1 )) !== -1 ) {
( last.m ) && ( last.i += needle.length, out += replacement );
out += str.substring( last.i, res );
last.i = res;
last.m = needle;
}
}
return out + str.substring( last.i );
}
var str = replaceAllBarLast(
"How about a how about b how about c",
/how about\s*/gi,
''
);
console.log(str);
Upvotes: 1
Reputation: 348
Regardless of language, there is no built-in method to do that. What you can do is something like (may require debugging)
string customReplace(string original, string replaceThis, string withThis)
{
int last = original.lastIndexOf(replaceThis);
int index = s.indexOf(replaceThis);
while(index>=0 && index < last )
{
original = original.left(index)+ original.right(index+replaceThis.length);
last = original.lastIndexOf(replaceThis); // gotta do this since you changed the string
index = s.indexOf(replaceThis);
}
return original; // same name, different contents. In C# is valid.
}
Upvotes: 0
Reputation: 66304
One way would be to use some kind of loop that checks to see if anything happened..
function allButLast(haystack, needle, replacer, ignoreCase) {
var n0, n1, n2;
needle = new RegExp(needle, ignoreCase ? 'i' : '');
replacer = replacer || '';
n0 = n1 = n2 = haystack;
do {
n2 = n1; n1 = n0;
n0 = n0.replace(needle, replacer);
} while (n0 !== n1);
return n2;
}
allButLast("How about a how about b how about c", "how about ", '', 1);
// "a b how about c"
Upvotes: 3