简体   繁体   中英

how to replace javascript '\' with another char

i have a var in javascript that looks like this:

C:\docs\path\file.exe

how can i replace \\ with another char like ? so the var becomes

C:?docs?path?file.exe

edit
i am trying to find the size of a file in JS. the only way i managed to do it, is to call a [WebMethod] using $ajax. when i try to send the path as it is, i get an escape character error, so i chose to replace '\\' by '?' and then the [WebMethod] replaces '?' with '\\' check the file size and returns it.

You can do this:

yourVar = yourVar.replace(/\\/g, '?');

The backslash has to be doubled in the regular expression because it's special in that syntax. Otherwise, it's pretty simple.

var path = "C:\\docs\\path\\file.exe";
path = path.replace(/\\/g,"?");
alert(path);

You need to escape the "\\" characters for this to work properly.

escape the \\ with \\\\ so

document.write(myPath.replace("\\\\", "?"));

var path = "C:\\docs\\path\\file.exe"
path ; //# => C:\docs\path\file.exe
path = path.replace(/\\/g, '?');
path ; //# => C:?docs?path?file.exe

have u tried this ?

var str = "C:\docs\path\file.exe"
var newStr = str.replace(/\\/g,"?")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM