Simplify replaceWith method. Closes gh-1276

(cherry picked from commit 1d57ffe5fff06928aac53813342d33ec6bddd531)