String replace all occurance of \" , "{ and "}

deepak50
Tera Contributor

Hi ,
I have to replace all occurances of  \" , "{ and "} from response of API. I am using replaceAll function of string as below but it is not working

var str2=responseBody.toString().replaceAll('\"','"');
var str3=str2.replaceAll('"{','{');
var str4=str3.replaceAll('"}','}');

This is not replacing these char , Please let me know how can we replace all chars as required.

Thanks
Deepak

1 ACCEPTED SOLUTION

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Deepak,

Can't replace backslash because it's an escape character. Backslash and the next character will be treated as 1 character in JavaScript. This is JavaScript specification.

View solution in original post

14 REPLIES 14

For example, the length of string '\"' is 1 and not 2.

var str = '\"';
gs.info('length:' + str.length);

Execution result:

*** Script: length:1

Kartik Sethi
Tera Guru
Tera Guru

Hi @deepak 

 

Is it possible to share the payload that you are receiving?

 

Thanks and regards,

Kartik

Kartik Sethi
Tera Guru
Tera Guru

Hi @deepak 

You can try below-provided logic:

var str = 'This is test \"value inside double quotes\" and opening curly braces "{ with closing curly braces "}';
str = str.replace(/\","/g);
str = str.replace("\"{","{");
str = str.replace("\"}","}");

console.log(str);

 


Please mark my answer as correct if this solves your issues!

If it helped you in any way then please mark helpful!

 

Thanks and regards,

Kartik

ra00119681
Kilo Contributor

Hi Deepak, did you find any resolution to this. I am in the same where I am trying to parse my input json file but failing as I am unable to trim escape sequence.

Hi,

I used replace function as below:

.replace(/\}"/g, '}')

you can refer javascript replace function for escape sequence.