Mohamed Nagy Mohamed Nagy - 1 year ago 72
Java Question

Remove backslashes in string

In my

page I have
list with multiple selection , and I store these values in an array of
, then I'm converting the array to a String that has this format:
. So it can work with the
operator of
SQL server

But the problem is that after the
is converted into a
each element is surrounded with backslashes. Like so:

I have used
String.replaceAll("\\\\", "");
which was working fine in another
Java application
. I am unsure why it doesn't work with my
solution (web Application).

here is my code :

String[] Names = request.getParameterValues("Name");
String Name = "(";
for (int i = 0; i < Names.length; i++) {
Name += "'".concat(Names[i]).concat("'") + ',';
Name = Name.concat(")");
Name = Name.replace(",)", ")");
Name = Name.replaceAll("\\\\", "");

I know that
Name = Name.replaceAll("\\\\", "");
will remove the backslashes but I don't know why it's not working in the servlet ?!

Is there a problem with values from the

Answer Source

Try using something like:

String[] names = request.getParameterValues("Name");
StringBuilder name = new StringBuilder("(");
for(int index = 0; index <names.length; index++){
    names[index] = names[index].replace("\\","");
    names[index] = names[index].replace("/","");
    name.append(index != names.length -1? "," : ")");
String output = name.toString();

The replace() method replaces every instance of the sub string, therefore you do not have to use "\\\\" unless of course if you only want to remove the double slashes and leave the single slashes.

If the problem persists then there are two possible reasons for it.

  1. The debugger expresses ' as \', so there should be no problem when sending the query to the server.
  2. The \ is not actually a slash or backslash but another character that looks like as backslash. You can find which character it is by using int test = output.charAt(output.length() - 3); and then check the value of the test variable using the debugger.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download