0

I have a string \"somedata\". I want to remove "\" character to result as "somedata". I tried var mystring = mystring.replace("\","");,however the result is incorrect. Can anyone help?

2
  • Can you add complete code Commented May 3, 2016 at 13:23
  • @Tushar The wrong way of escaping is the problem here. Commented May 3, 2016 at 13:24

2 Answers 2

3

try following:

mystring.replace(/\\/g,"");
Sign up to request clarification or add additional context in comments.

Comments

2

The \ is an escape character. To use \, you need to escape it twice:

mystring.replace("\\","");

Explanation

When you give this:

mystring.replace("\","");

The JavaScript thinks, you wanna insert a " there and will not find the ending double quotes. The string will be incomplete here.

var some = '\\"somedata\\"';
alert("Before: " + some);
some = some.replace("\\", "");
alert("After: " + some);

But the above code replaces only one occurrence. You need to use RegEx to replace all the occurrences.

var some = '\\"somedata\\"';
alert("Before: " + some);
some = some.replace(/\\/g, "");
alert("After: " + some);

You can use the g tag for global.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.