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);