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

Adrian Ubeda
Mega Sage
Mega Sage

Hi deepak,

Try to create a regex expression as variable and then add it into code, I've try this in bg script and worked:

//code
var regex = '\"';
var str1 = 'this is a test\"';
var str2=str1.toString().replaceAll(regex,'"');

gs.info('str2 ->' + str2);
// output
*** Script: str2 ->this is a test"

If it was helpful, please give positive feedback.
Thanks,

If it was helpful, please give positive feedback! ✔
☆ Community Rising Star 22, 23 & 24 ☆

Hi I tried this code , it is showing str1 and str2 same in output:

str1 ->this is a test"
str2 ->this is a test"

That is not a regex. That is a string. This is a regex

var regex = /"/;

Plus in ServiceNow replaceAll does not work with regular expressions. Which in my opinion is a serious bug.

Substituting replace() for replaceAll() will allow the use of regex, including /''/g

var paragraph = "I think Ruth's dog is cuter than your dogs!";

gs.info(paragraph.replace('dog', 'monkey'));
// Expected output: "I think Ruth's monkey is cuter than your monkeys!"


// Global search/replace:

var regex = /dogs?/g;
gs.info(paragraph.replace(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your ferret!"