24

I have string with file path. I want to replace all single backslashes ("\") with double backslashes ("\\").

   var replaceableString = "c:\asd\flkj\klsd\ffjkl";
   var part = /@"\\"/g;
   var filePath = replaceableString .replace(part, /@"\\"/);
   console.log(filePath);

Console showed me it.

   c:asdlkjklsdfjkl

I found something like this, unfortunately it didn't work. Replacing \ with \\

Community
  • 1
  • 1
PilgrimViis
  • 1,511
  • 2
  • 17
  • 21

10 Answers10

14

Try:

   var parts = replaceableString.split('\\');
   var output = parts.join('\\\\');

Personally, as I am not so expert in reg exps, I tend to avoid them when dealing with non-alphanumeric characters, both due to readability and to avoid weird mistake.

LittleSweetSeas
  • 6,786
  • 2
  • 21
  • 26
11
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
alert(replaceableString);

This will alert you c:asdlkjklsdfjkl because '\' is an escape character which will not be considered.

To have a backslash in your string , you should do something like this..

var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
alert(replaceableString);

This will alert you c:\asd\flkj\klsd\ffjkl

JS Fiddle

Learn about Escape sequences here

If you want your string to have '\' by default , you should escape it .. Use escape() function

var replaceableString = escape("c:\asd\flkj\klsd\ffjkl");
alert(replaceableString);

JS Fiddle

Prasath K
  • 4,950
  • 7
  • 23
  • 35
10

You have several problems in your code.

  1. To get a \ in your string variable you need to escape it.

    When you create a string like this: replaceableString = "c:\asd\flkj\klsd\ffjkl"; characters with a \ before are treated as escape sequences. So during the string creation, it tries to interpret the escape sequence \a, since this is not valid it stores the a to the string. E.g. \n would have been interpreted as newline.

  2. I assume the @ is coming from a .net example. Javascript does not know "raw" strings.

  3. remove the quotes from your regex.

This would do what you want:

var string = "c:\\asd\\flkj\\klsd\\ffjkl";
var regex = /\\/g;
var FilePath = string.replace(regex, "\\\\");
Community
  • 1
  • 1
stema
  • 90,351
  • 20
  • 107
  • 135
6

Here is the answer:

For replacing single backslash with single forward slash:

var stringReplaced = String.raw`c:\asd\flkj\klsd\ffjkl`.split('\\').join('/')
console.log(stringReplaced);

For replacing double backslash with single forward slash:

var stringReplaced = String.raw`c:\\asd\\flkj\\klsd\\ffjkl`.split('\\\\').join('/')
console.log(stringReplaced);
Siluveru Kiran Kumar
  • 699
  • 1
  • 10
  • 16
  • 1
    This is not the answer, as the question was not how to replace with a forward slash to begin with. – Forage May 21 '21 at 13:44
4

\ is a escape character. Therefore replaceableString does not contain any backslashes.

To fix this you should declare the string like this:

var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
Leon Lucardie
  • 9,541
  • 4
  • 50
  • 70
  • The fact that the user enters the path itself in the input field. Handle administered line in real time, and replace all "\" pressed key? – PilgrimViis Apr 22 '13 at 10:04
  • @user2075057 Make it clear user inputs the path with '\' so you want it to remain it in your string...?? I mean not to escape ...?? – Prasath K Apr 22 '13 at 10:13
  • @Prasath K I want to display something from file using my java code. – PilgrimViis Apr 22 '13 at 10:20
  • @Prasath K Also I want to save information from input field in same file. This is needed to my service. This task I decided, but if I have to enter the double slashes, it is not a pretty sight – PilgrimViis Apr 22 '13 at 10:22
  • @user2075057 escape your input string and use it to open or save the file .. I mean escape('c:\asd\flkj\klsd\ffjkl'); .. Check my edited answer – Prasath K Apr 22 '13 at 10:24
  • If you retrieve the replaceableString as an object from an input field the character escaping won't be neccesary. Backslash characters only need escaping when used in string literals. See: http://java.about.com/od/understandingdatatypes/a/The-String-Literal.htm – Leon Lucardie Apr 22 '13 at 10:27
  • Thanks to you all, I found the solution! I simply replace the backslashes in my java function. In javascript will come string like this "c:\\asd\\flkj\\klsd\\ffjkl". I think it should work. – PilgrimViis Apr 22 '13 at 10:39
4

First encode the string

then replace all occurrences of %5C with %5C%5C

At the end decode the string

var result = encodeURI(input);
result=decodeURI(result.replace(/%5C/g,"%5C%5C"));
omkar1707
  • 75
  • 1
  • 6
0

If you have no control over the contents of the string you are trying to find backslashes in, and it contains SINGLE \ values (eg. variable myPath contains C:\Some\Folder\file.jpg), then you can actually reference the single backslashes in JavaScript as String.fromCharCode(92).

So to get the file name in my filepath example above.

var justTheName = myPath.split(String.fromCharCode(92)).pop();
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
thegajman
  • 559
  • 4
  • 2
0

In case of string matching, it is better to use encodeURIComponent, decodeURIComponent.

match(encodeURIComponent(inputString));

function match(input)
{

for(i=0; i<arr.length; i++)
{
if(arr[i] == decodeURIComponent(input))
return true;
else return false;
}
}
-1

In the case of a single back slash in the string, the javascript replace method did not allow me to replace the single back slash.

Instead I had to use the split method which returns an array of the split strings and then concatenate the strings without the back slash (or whatever you want to replace it with)

Solution (replaced backslash with underscore):

var splitText = stringWithBackslash.split('\\');
var updatedText = splitText[0] + '_' + splitText[1];
Geoff
  • 1
-1

You need to pass to pass value of a string through String.raw before you assign value to a variable.

var replaceableString = String.raw`c:\asd\flkj\klsd\ffjkl`.replace(/\\/g,"\\\\");
console.log(replaceableString)