- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2022 03:36 AM
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
Solved! Go to Solution.
- Labels:
-
Integrations
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2022 09:36 PM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2022 03:44 AM
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,
☆ Community Rising Star 22, 23 & 24 ☆
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-25-2022 04:50 AM
Hi I tried this code , it is showing str1 and str2 same in output:
str1 ->this is a test"
str2 ->this is a test"
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
04-01-2024 05:43 PM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-14-2024 11:38 PM - edited 12-14-2024 11:46 PM
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!"