DEV Community

Taufik Nurrohman
Taufik Nurrohman

Posted on • Updated on

Match Valid RGB/RGBA Color String using Range Pattern

First, we need to match range from 0 to 9. This range is safe enough so you can just:

let range = /^[0-9]$/;
Enter fullscreen mode Exit fullscreen mode

Then match range from 10 to 99:

let range = /^([0-9]|[1-9][0-9])$/;
Enter fullscreen mode Exit fullscreen mode

Then match range from 100 to 199:

let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9])$/;
Enter fullscreen mode Exit fullscreen mode

Then match range from 200 to 249:

let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9])$/;
Enter fullscreen mode Exit fullscreen mode

Last, match range from 250 to 255:

let range = /^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|2[0-5][0-5])$/;
Enter fullscreen mode Exit fullscreen mode

You can narrow down the range pattern using alternative syntax. For example, use \d in place of [0-9]:

let range = /^(\d|[1-9]\d|1\d{2}|2[0-4]\d|2[0-5]{2})$/;
Enter fullscreen mode Exit fullscreen mode

Test it!

for (let i = -100; i < 300; ++i) {
    if (range.test(i + "")) {
        console.log('[' + i + ']');
    } else {
        console.log(i);
    }
}
Enter fullscreen mode Exit fullscreen mode

Matching RGB color string using the range pattern (with permissive white-spaces):

let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';

let rgb = new RegExp('^rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)$');
Enter fullscreen mode Exit fullscreen mode

To match RGBA color string, you need to create alpha range. First, match range from 0 to 1:

let alpha = /^(0|1)$/;
Enter fullscreen mode Exit fullscreen mode

Then match the decimal point prefixed by 0:

let alpha = /^(0|0\.[0-9]+|1)$/;
Enter fullscreen mode Exit fullscreen mode

Sometimes, leading zero is not required, so:

let alpha = /^(0|0?\.[0-9]+|1)$/;
Enter fullscreen mode Exit fullscreen mode

Narrow down the pattern:

let alpha = /^([01]|0?\.\d+)$/;
Enter fullscreen mode Exit fullscreen mode

To match RGBA color string:

let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';

let rgb = new RegExp('^rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\)$');
Enter fullscreen mode Exit fullscreen mode

To match both RGB and RGBA color string:

let range = '(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|2[0-5]{2})';
let alpha = '([01]|0?\\.\\d+)';

let rgb = new RegExp('^(?:rgb\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*\\)|rgba\\(\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + range + '\\s*,\\s*' + alpha + '\\s*\\))$');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)