Replace Single Backslash With Double Backslash

Replace single backslash "\" with double backslashes "\\"

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

Replacing all backslash with double backslashes in bash

You can use sed for that:

echo "hello\world\hello\world" | sed 's/\\/\\\\/g'

Outputs:

hello\\world\\hello\\world

Replace single backslash with double backslash

The first one should be "\\\\", not "\\". It works like this:

  • You have written "\\".
  • This translates to the sequence \ in a string.
  • The regex engine then reads this, which translates as backslash which isn't escaping anything, so it throws an error.

With regex, it's much easier to use a "verbatim string". In this case the verbatim string would be @"\\". When using verbatim strings you only have to consider escaping for the regex engine, as backslashes are treated literally. The second string will also be @"\\", as it will not be interpreted by the regex engine.

python replace single backslash with double backslash

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'

Below is the repr version of the above string, that's why you're seeing \\ here.
But, in fact the actual string contains just '\' not \\.

>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'

>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\' in the output.

>>> print strs
C:\Users\Josh\Desktop\20130216

If you want the string to show '\\' during print then use str.replace:

>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216

repr version will now show \\\\:

>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'


Related Topics



Leave a reply



Submit