Home > Software design >  Replace '\\' with '\' in javascript
Replace '\\' with '\' in javascript

Time:12-17

Data: Input let x = "«Pe.¯­\\x02`ä¦c\\x0E,ÞHä"

Expected Output: «Pe.¯­\x02`ä¦c\x0E,ÞHä

CodePudding user response:

Substitution Pattern: \\(\\)

Demo: https://regex101.com/r/rTaxgS/1

CodePudding user response:

The code you posted already produces the desired string because \\ in string literals produces \.

let x = "«Pe.¯­\\x02`ä¦c\\x0E,ÞHä";
console.log(x);                           // «Pe.¯­\x02`ä¦c\x0E,ÞHä


But let's say you started with

«Pe.¯­\\x02`ä¦c\\x0E,ÞHä

In that case, you could use the following:

let x = "«Pe.¯­\\\\x02`ä¦c\\\\x0E,ÞHä";
console.log(x);                           // «Pe.¯­\\x02`ä¦c\\x0E,ÞHä
x = x.replace(/\\\\/g, "\\");             // Replace each pair of `\` with one.
console.log(x);                           // «Pe.¯­\x02`ä¦c\x0E,ÞHä

  • Related