0

I need to send the folder path to MySQL. So I have escaped each backslash. The path to be sent via javascript will be :

\\\\192.168.0.1\\foo\\bar

This will ultimately be saved as (in db):

\\192.168.0.1\foo\bar

So, I wrote the following code:

        fpath = fpath.replace(/\\+/g,'\\\\'); // Replace multiple occurences of backslash with double backslash

        var fpathLen = fpath.length;

        if(fpath.charAt(fpathLen-1) == '\\')
            fpath = fpath.substring(0,fpathLen-2); // Remove the trailing backslash if any

        if(fpath.charAt(0) == '\\') {
            fpath = '\\\\' + fpath;  // Add 2 more backslash before sending the string to MySQL
        }
        else
            fpath = '\\\\\\\\' + fpath; // If string is without a leading backslash, insert 4 backslash

But it doesn't seem to be an effective way of doing things! For example, I have manually added 4, in another case 8 backslashes to make it 2 and 4 respectively on js side. Is there a better way of achieving this?

Edit: For an input path like fpath = \\1.1.1.1\\\\\\\\foo\bar\\\config , output should be \\\\192.168.0.1\\foo\\bar

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

2

EDIT:

You can do this by two regex:

fpath = fpath.replace(/\\+/g,'\\\\');

and

fpath = fpath.replace(/^\\*(.*?)\\*$/,'\\\\\\\\$1');

Demo:

function makeFpath() {
  fpath = document.getElementById("fpath").value
  fpath = fpath.replace(/\\+/g, '\\\\').replace(/^\\*(.*?)\\*$/, '\\\\\\\\$1');

  document.getElementById("out").innerHTML = fpath
}

makeFpath()
<input id="fpath" onkeyup="makeFpath()" onchange="makeFpath()" value="\\\1.1.1.1\\\\\\\\foo\bar\\\config\" style="width: 100%" />
<div id="out"></div>

OLD: I think you got a little messed up with all the escaping*, is this doing it for you? :

fpath = fpath.replace(/\\/g,'\\\\'); // replaces a single \ by one double \\

you don't anything else if I understood your problem correctly

CoderPi
  • 12,985
  • 4
  • 34
  • 62