Replace single backslash with double. How does it effect string that already have double backslah

nishtha3
Kilo Contributor

Hi ,

I'm using the below code to escape single backslash that is present in my JSON payload

json_payload.replace("\\","\\\\");

This works fine when the payload contains single backslash. eg {"name": "\xyz"}

This gets converted to {"name": "\\xyz"}

but the cases where there are 2 backslash already {"name": "\\abc"} the output is {"name": "\\\\abc"}

As far a I know as backslash is special character in JS, we need to escape each single (\) with double(\\), and that is what my code does, why does it effect the already double(\\).

Nisha

6 REPLIES 6

asifnoor
Kilo Patron

Hi Nitisha,

Can you share your exact code.

nishtha3
Kilo Contributor

I'm getting JSON data populated on one of the fields when a new record is created on a table. I'm querying that table in an on before BR and checking for (\\), if it contains replace it with(\\\\)

var outbounddata = current.u_outbound_data;
if(outbounddata.contains("\\")){
var outbounddata = outbounddata.replace("\\","\\\\");
}

 

Hi Nishtha,

It does because the replace will look for each \ and replace it with double \\.

 

Hi Nishtha,

Try this code. This should work.

var outbounddata = current.u_outbound_data;
if(outbounddata.contains("\\")){ 
   var outbounddata = outbounddata.replace(/\\+\b/g,'\\\\');
}


Mark the comment as a correct answer and also helpful once worked.