diff --git a/src/ol/color.js b/src/ol/color.js index b48f149e90..e523d94336 100644 --- a/src/ol/color.js +++ b/src/ol/color.js @@ -223,3 +223,14 @@ export function toString(color) { const a = color[3] === undefined ? 1 : color[3]; return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; } + +/** + * @param {string} s String. + * @return {boolean} Whether the string is actually a valid color + */ +export function isStringColor(s) { + if (NAMED_COLOR_RE_.test(s)) { + s = fromNamed(s); + } + return HEX_COLOR_RE_.test(s) || s.indexOf('rgba(') === 0 || s.indexOf('rgb(') === 0; +} diff --git a/test/spec/ol/color.test.js b/test/spec/ol/color.test.js index b230e289ad..a4099e747d 100644 --- a/test/spec/ol/color.test.js +++ b/test/spec/ol/color.test.js @@ -2,6 +2,7 @@ import { asArray, asString, fromString, + isStringColor, normalize, toString } from '../../../src/ol/color.js'; @@ -159,4 +160,18 @@ describe('ol.color', function() { }); }); + + describe('isValid()', function() { + + it('correctly detects valid colors', function() { + expect(isStringColor('rgba(1,3,4,0.4)')).to.be(true); + expect(isStringColor('rgb(1,3,4)')).to.be(true); + expect(isStringColor('lightgreen')).to.be(true); + expect(isStringColor('yellow')).to.be(true); + expect(isStringColor('GREEN')).to.be(true); + expect(isStringColor('notacolor')).to.be(false); + expect(isStringColor('red_')).to.be(false); + }); + + }); });