2

I'm trying to replace backslashes in my string with two backslashes like so:

s = s.replace("\\", "\\\\");

But, it doesn't do anything. Example string:

s="\r\nHi\r\n";
6
  • when you print the string (before the replace), does it show one or two backslashes? Commented Aug 3, 2013 at 19:58
  • @user2049371 one more option posted Commented Aug 3, 2013 at 20:06
  • 2
    The string in your example ("\r\nHi\r\n") does not contain a backslash. \r is the escape sequence for a carriage return and \n is the escape sequence for a line feed. The resulting string value does not contain the backslash character. Just do console.log(s) and you will see. If you'd explain what problem you are really trying to solve, we might be able to help you. Commented Aug 3, 2013 at 20:16
  • @user2049371 What Felix said is correct, the string does't contain escape sequences. View my example Commented Aug 3, 2013 at 20:18
  • jsfiddle.net/wC8Cc/29 Commented Aug 3, 2013 at 20:21

1 Answer 1

2

The string doesn't contain a backslash, it contains the \r escape sequence.

Working example

For example

var str = "\r\n";
var replaced = str.replace('\r\n', '\\r\\n');
alert(replaced);

Then the alert will be shown \r\n

Sign up to request clarification or add additional context in comments.

2 Comments

@user2049371 one more option posted
for help => s = "\r\n" ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.