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"
Share
Improve this question
edited Mar 23, 2017 at 12:25
Donald Duck
8,89223 gold badges79 silver badges102 bronze badges
asked Oct 12, 2010 at 10:29
maheshmahesh
3,21717 gold badges72 silver badges131 bronze badges
2
- How do you generate that line? The solution should be on server side, before JavaScript. – Kobi Commented Oct 12, 2010 at 10:36
-
Using regex it is hard to replace '/' with other string. So we can use
String.replaceAll()
. Source: link – jayanthsaikiran Commented Feb 21, 2021 at 9:31
5 Answers
Reset to default 14You 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..
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.
Try this :
str.replace(new RegExp('/', 'g'),'-')
Just add after var imagepath initialisation
var imagepath=imagepath.replace("\", "\\");
return imagepath;