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?
-
Can you add complete codeTushar– Tushar2016-05-03 13:23:53 +00:00Commented May 3, 2016 at 13:23
-
@Tushar The wrong way of escaping is the problem here.Praveen Kumar Purushothaman– Praveen Kumar Purushothaman2016-05-03 13:24:30 +00:00Commented May 3, 2016 at 13:24
Add a comment
|
2 Answers
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.