node.jsstringurlcachingregexp-replace

How to replace multiple slashes with backslashes in URL string in Node.js environment?


I cache images in a directory after fetching them from different URLs. The cache files must identify the URL precisely so, in my ext4 file system where NUL and / chars are not allowed in file names, I thought of replacing.

> "https://abc.def/ghi".replace(/\//g, "\\")
'https:\\\\abc.def\\ghi'

I want the output to be:

'https:\\abc.def\ghi'

What is wrong?


Solution

  • 'https:\\\\abc.def\\ghi' is actually, if printed with console.log, https:\\abc.def\ghi

    When printing the 4-backslashes version, the Node.js console escapes the \ into \\.