Fix border case in which replace function would replace the wrong part of the string