Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  152] [ 2]  / answers: 1 / hits: 28366  / 10 Years ago, thu, august 14, 2014, 12:00:00

I have the following problem:



I have a script that executes an AJAX request to a server, the server returns C:backup in the preview. However, the response is C:\backup\. Not really a big deal, since I just thought to replace the double slashes with single ones. I've been looking around here on stack, but I could only find how to replace single backslashes with double ones, but I need it the other way around.



Can someone help me on this matter?


More From » ajax

 Answers
23

This should do it: "C:\backup\".replace(/\\/g, '\')


In the regular expression, a single must be escaped to \, and in the replacement also.


[edit 2021] Maybe it's better to use template literals.




console.log(`original solution ${C:\backup\.replace(/\\/g, '\')}`)

// a template literal will automagically replace \ with
console.log(`template string without further ado ${`C:\backup\`}`);

// but if they are escaped themselves
console.log(`Double escaped ${`C:\\backup\\`.replace(/\{2,}/g, '\')}`);

// multiple escaped
console.log(`multiple escaped ${`C:\\\\backup\\`
.replace(/\{2,}/g, '\')}`);

// don't want to replace the last \
console.log(`not the last ${`C:\\\backup\\`
.replace(/\{2,}([^\{2,}$])/g, (a ,b) => a.slice(0,1) + b)}` );

// don't want to replace the first \
console.log(`not the first ${`C:\\backup\`.replace(/\[^\]$/g, '\')}`);

// a generic tagged template to replace all multiple \ OR //
const toSingleSlashes = (strs, ...args) =>
strs.reduce( (a, v, i ) =>
a.concat(args[i-1] || ``).concat(v, ``), `` )
.replace( /(\|/){2,}/g, (a, b) => b );

console.log(`generic tagged template 1 ${
toSingleSlashes`C:\backup\`}`);

console.log(`generic tagged template 2 ${
toSingleSlashes`C:\\\\backup\\\\\`}`);

console.log(`generic tagged template 3 ${
toSingleSlashes`C:\\\\backup\`}`);

console.log(`generic tagged template 4 ${
toSingleSlashes`C:////////backup////`}`);

console.log(`reply to comment @chitgoks =>
test\\hehehe is by default test\hehehe
so, no replacement necessary here ...`);

.as-console-wrapper {
max-height: 100% !important;
}




[#69786] Tuesday, August 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
nolancampbellc questions
Thu, Sep 23, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;