mahesh -4 years ago 129
Javascript Question

# how to replace \ with \\ using javascript string functions

I have the following filepath

``````var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
``````

how can i replace \ with \ so so that it prints

``````var imagepath="C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"
``````

You need to use the replace() method whilst escaping the `\` character on each occurrence:
``````imagepath = imagepath.replace(/\\/g, "\\\\");
If `imagepath` is defined with single backslash characters, those will be evaluated into an escape sequence along with the character(s) following them. At this point it's too late to replace the backslashes as they are removed from the resulting string.