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"
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, "\\\\");
//-> "C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"
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.
It's a string literal.. By the time it's assigned to imagepath, the escape sequences are already parsed and processed, and the backslashes no longer exist in the string. You just have to have them in the string in the first place.
To demonstrate what I mean:
>>> var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
>>> imagepath
"C:Documents and SettingsMaheshDesktopimagesadvts.png"
There's no way to fix the issue at that stage.
You can use the string replace()
method. Replace on W3Schools.com.
Example:
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
document.write(imagepath.replace("\\", "\\\\"));
Upate As reko_t said, once a path is assigned to imagepath
, it's a processed literal. The \
characters disappears. I've just tested my code with this example and there's no way to fix it unfortunately.
<html>
<head>
<script type="text/javascript">
function init() {
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
alert(imagepath.replace(/\\/g, "\\\\"));
}
</script>
</head>
<body onload="init()">
</body>
</html>
The only way to do it, is to replace \
to \\
on server side, and assign it to imagepath
before it gets rendered to javascript that needs to be used by javascript.
Just add after var imagepath initialisation
var imagepath=imagepath.replace("\", "\\");