We have a requirement to replaces the single backslash with double backslash

Ezhil2
Tera Contributor

Path=From \\test1\test2\test3

 

While passing the above path in API getting error due to the Back slash included in the path. We need to replace single backslash with double backslash.

 

 

2 REPLIES 2

raj chavan
Tera Guru

var path = "\\test1\\test2\\test3";
var modifiedPath = path.replace(/\\/g, "\\\\"); // Replaces single with double 

gs.info("Original Path: " + path);
gs.info("Modified Path: " + modifiedPath);

If my answer helped you in any way, then mark it as helpful or correct. This will help others finding a solution.

Kindly mark it correct and helpful if it is applicable.

Thanks,

Raj

Mark Manders
Mega Patron

Check if this will work for you:

var path = "From \\test1\test2\test3";

// Replace only single backslashes, not already doubled ones
var sanitizedPath = path.replace(/(^|[^\\])\\([^\\]|$)/g, "$1\\\\$2");

console.log(sanitizedPath); 

 

This should check if a backslash is already preceded or followed by a backslash and if so, ignores it.


Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark