improve replace logic