Reputation: 644
i wanted to save the json object with one escape character by escaping "/" so i used string replace and convert my string into "/" then i assigned this to an object variable and tried to console log it will auto convert to "\/"
my initial dataset is base64 string
here is my code snippet
sample string : data ="/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
var datawithescape= data.replace(/\//g, '\\/');
console.log("result 1"+ datawithescape);
var result ={
"id" : id,
"data":datawithescape
};
console.log("result 2" +result);
outputs
result 1
"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
result 2
{
id :1
data : "\\/9j\\/4AAQSkZJRgABAQAAAQABAAD\\/\\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
}
what i want is
{
id :1
data : "\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
}
Upvotes: 0
Views: 936
Reputation: 5581
The problem you're having is that console.log
is formatting the string for you in different ways. The data itself hasn't changed.
When console.log
shows an object it shows the full internal representation of the data, which includes escape characters. When it formats as a string, it shows the character, not its escaped form.
Consider this smaller example in REPL:
> let x = "\\/abc\\/"
'\\/abc\\/' <--- first character is an escaped backslash "\\"
> let y = {x: x}
{ x: '\\/abc\\/' } <--- first character in y.x is still an escaped backslash
> console.log(y)
{ x: '\\/abc\\/' } <--- same result when console.log shows 'y'
> console.log(x)
\/abc\/ <--- but here console.log displays x without the escape
> console.log(y.x)
\/abc\/ <--- similarly here for y.x
> let z = "\tHello"
> z
'\tHello' <--- when looking at z as an object we see "\t"
> console.log(z)
Hello <--- when looking at z as a string we see the tab expanded
In your example, if you do console.log(result.data)
you will see it without the double backslash as you want. When showing the object rather than the formatted string, console.log
shows you the actual data which has an escaped backslash and hence shows as '\'.
Upvotes: 1
Reputation: 2039
Its working fine here. unable to share answer in comments so sharing here.
Edit: adding one more pic on new data;
Upvotes: 0