Replace with a single backslash in javascript?

javascript, latex, node.js, regex, replace

Solution

Actually, the first method is correct and works. Two backslash is indeed used to make a single backslash.

console.log("hello & 100%".replace(/([&%$#_{}])/g, "\\$1")); // "hello \& 100\%"

If `console.log` is giving you some trouble, which it shouldn't, try `alert`. Also you need to use the return value which you aren't doing.

Problem

I'm creating a latex templating system using Node.js. As part of this system, I need to escape any characters with special meanings by prefixing them with a backslash. I've read that a double-backslash is used to insert a literal backslash: ``` > var input = "hello & 100%" > input.replace(/([&%$#_{}])/g, "\\$1") 'hello \\& 100\\%' ``` Nope. I've also read that because it's inside a string, I need to double-escape the backslash: ``` > input.replace(/([&%$#_{}])/g, "\\\\$1") 'hello \\\\& 100\\\\%' ``` Nope. And using just one backslash doesn't do it either: ``` > input.replace(/([&%$#_{}])/g, "\$1") 'hello & 100%' ``` So how am I supposed to insert a single backslash using `replace()`?

Original source