How do I add slashes to a string in Javascript? June 4, 2023 by Tarik replace works for the first quote, so you need a tiny regular expression: str = str.replace(/'/g, "\\'");