MCPcopy Create free account
hub / github.com/SeleniumHQ/selenium / escape

Method escape

java/src/org/openqa/selenium/support/ui/Quotes.java:36–60  ·  view source on GitHub ↗

Convert strings with both quotes and ticks into a valid xpath component For example, foo will be converted to "foo", f"oo will be converted to 'f"oo', foo'"bar will be converted to concat("foo'", '"', "bar") @param toEscape a text to e

(String toEscape)

Source from the content-addressed store, hash-verified

34 * @return the same text with escaped quoted, e.g. {@code "\"f'oo\""}
35 */
36 @SuppressWarnings("JavaDoc")
37 public static String escape(String toEscape) {
38 if (toEscape.contains("\"") && toEscape.contains("'")) {
39 boolean quoteIsLast = toEscape.lastIndexOf("\"") == toEscape.length() - 1;
40 String[] substringsWithoutQuotes = toEscape.split("\"");
41
42 StringBuilder quoted = new StringBuilder("concat(");
43 for (int i = 0; i < substringsWithoutQuotes.length; i++) {
44 quoted.append("\"").append(substringsWithoutQuotes[i]).append("\"");
45 quoted.append(
46 ((i == substringsWithoutQuotes.length - 1)
47 ? (quoteIsLast ? ", '\"')" : ")")
48 : ", '\"', "));
49 }
50 return quoted.toString();
51 }
52
53 // Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
54 if (toEscape.contains("\"")) {
55 return String.format("'%s'", toEscape);
56 }
57
58 // Otherwise return the quoted string
59 return String.format("\"%s\"", toEscape);
60 }
61}

Calls 5

splitMethod · 0.80
lengthMethod · 0.65
toStringMethod · 0.65
appendMethod · 0.45
formatMethod · 0.45