Search code examples
javaseleniumselenium-webdriverwebdriverdouble-quotes

How to pass double quoted strings through sendKeys method using Selenium and Java


I am working on a selenium script where 3 values are being fetched and store in String.

String one = "19292";
String two = "Abc";
String three = "def";

I want it to send text as (one + two + three) but all of them is having double quotes. So end result should be "19292""Abc""def"

How can I do this ?

I have tried using the escape mechanism using back slash, but whenever I use it rather than fetching the string value it prints the text. For Eg :

\"one\" prints "one" rather than "19292"

Solution

  • Try sth like this:

    field.sendKeys("\"" + one + "\"\"" + two + "\"\"" + three + "\"");
    

    I just checked with selenium and it works. The input which goes to field is : "19292""Abc""def"

    Or if you don't know the number of Strings then below is the method which will convert in quotes format.

    public static void main(String[] args) {
        String one = "19292";
        String two = "Abc";
        String three = "def";
    
        System.out.println(surroundWithDoubleQuotes(one, two, three));
    
    
    }
    
    public static String surroundWithDoubleQuotes(String... input) {
        if(input == null || input.length == 0) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for(String arg : input) {
            builder.append("\"\"");
            builder.append(arg);
        }
        builder.append("\"");
        builder.deleteCharAt(0);
    
        return builder.toString();
    }