Szymon Toda Szymon Toda - 3 years ago 217
Javascript Question

How to escape backslash in JavaScript?

I want to replace backslash => '\' with secure


But my code replacing all '#' fails when applied for replacing '\':

el = el.replace(/\#/g, '#'); // replaces all '#' //that's cool
el = el.replace(/\\/g, '\'); // replaces all '\' //that's failing


Answer Source

open console and type

'\'.replace(/\\/g, '\'); 

fails because the slash in the string isn't really in the string, it's escaping '

'\\'.replace(/\\/g, '\');

works because it takes one slash and finds it.

your regex works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download