improve replace algorithm - shorter