Mohamed Nagy Mohamed Nagy - 25 days ago 8
Java Question

Remove backslashes in string

In my

jsp
page I have
dropdown
list with multiple selection , and I store these values in an array of
Strings
using
getParamterValues()
, then I'm converting the array to a String that has this format:
('x','y','z')
. So it can work with the
IN
operator of
SQL server
.

But the problem is that after the
array
is converted into a
String
each element is surrounded with backslashes. Like so:
(\'X\',\'Z\',\'Y\')
.

I have used
String.replaceAll("\\\\", "");
which was working fine in another
Java application
. I am unsure why it doesn't work with my
servlet
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
dropdown
list?

Answer

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("'");
    name.append(names[index]);
    name.append("'");
    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.