0

I am trying to parse a string like this

var temp = JSON.parse('{"FHPosition":"consultant","FDesc":"apr4","FHId":"i:0#.w|spdev\gkr"}'.replace("\\","\\\\"))
console.log(temp.FHId)

//expected output: i:0#.w|spdev\gkr
//actual output: i:0#.w|spdevgkr

But when I try to replace backslash or do any actions with string backslash vanishes from a string. Is there any way to replace backslash without it vanishing?

SIL0RAK
  • 7
  • 2
  • 4
  • 1
    The fact that your string _literal_ has a backslash in it, does not mean that your actual string has. Try to print it. There is no backslash in it. – Ivar Dec 18 '18 at 10:25

1 Answers1

0

As shown in this answer, unless the character after the backslash is a valid escape sequence (a list can be found here), it will remove the backslash from the string entirely. I believe you need to first use a regular expression in .replace(), and secondly you should stringify the data inside the parse statement before you replace it. Try using this code:

var temp = JSON.parse(JSON.stringify('{"FHPosition":"consultant","FDesc":"apr4","FHId":"i:0#.w|spdev\gkr"}').replace("\\","\\\\"))
console.log(temp.FHId);

Hopefully this helps!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79