Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert #ffffff to #fff or #fff to #ffffff while asserting the background color rgb(255,255,255) returned by Selenium getCssValue("background")

How to convert #ffffff to #fff or #fff to #ffffff for Assertion?

I am using getCssValue("background") from Selenium which returns rgb(255, 255, 255) which I can split into:

  • r -> 255
  • g -> 255
  • b -> 255

The following line of code:

String hex = String.format("#%02x%02x%02x", r, g, b);

Converts rgb to hex and gives an output as:

#ffffff

But from the console, the background is extracted as #fff

fff

So what can be the ideal way either to:

  • convert #ffffff to #fff
  • convert #fff to #ffffff

I have been through a couple of relevant discussions as:

  • Why use #fff color on body? which mentions that the issue is somewhat subjective.
  • CSS: Which is faster for the browser? color:#fff; or color:#ffffff; which mentions CSS compressors will intelligently optimize to the #fff version.

But my tests are failing and there is a need for conversion. Any recommendations?

like image 965
undetected Selenium Avatar asked Dec 02 '25 14:12

undetected Selenium


1 Answers

You can use replaceAll with a regular expression that looks for the case where all three parts use the same digit:

static String getHex(int r, int g, int b) {
    return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
}

That looks for a string starting with # followed by three pairs of matching hex digits, and replaces them with just the short form. (I suppose I could have just used [a-f] instead of [a-fA-F] in your specific example, since you know you'll be getting lower case only, but...)

Complete example (on Ideone):

public class Example {
    public static void main(String[] args) {
        System.out.println(getHex(255, 255, 255)); // #fff
        System.out.println(getHex(255, 240, 255)); // #fff0ff
    }

    static String getHex(int r, int g, int b) {
        return String.format("#%02x%02x%02x", r, g, b).replaceAll("^#([a-fA-F])\\1([a-fA-F])\\2([a-fA-F])\\3$", "#$1$2$3");
    }
}
like image 163
T.J. Crowder Avatar answered Dec 05 '25 04:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!