JavaScript / ECMAScript

CSS rgb() Color in JS

Match CSS rgb() and rgba() color functions, including an optional alpha channel.

Try it in the JS tester →

Pattern

regexJS
rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)   (flags: gi)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("rgba?\\(\\s*\\d{1,3}\\s*,\\s*\\d{1,3}\\s*,\\s*\\d{1,3}(?:\\s*,\\s*(?:0|1|0?\\.\\d+))?\\s*\\)", "gi");
const input = "rgb(255, 87, 51)";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

Matches rgb( or rgba( followed by three comma-separated 1–3 digit components and an optional fourth alpha component (0, 1, or decimal).

Examples

Input

rgb(255, 87, 51)

Matches

  • rgb(255, 87, 51)

Input

rgba(0, 0, 0, 0.5)

Matches

  • rgba(0, 0, 0, 0.5)

Input

color: blue;

No match

Same pattern, other engines

← Back to CSS rgb() Color overview (all engines)