繁体   English   中英

如何检查字符串是否是有效的十六进制颜色表示?

[英]How to check if a string is a valid hex color representation?

例如:

AA33FF = 有效的十六进制颜色

Z34FF9 = 无效的十六进制颜色(其中有 Z)

AA33FF11 = 无效的十六进制颜色(有额外的字符)

var isOk  = /^#[0-9A-F]{6}$/i.test('#aabbcc')

详细说明:

^匹配开始
#哈希
[a-f0-9]来自af和0-9的任何信件
{6}前一组正好出现6次
$ match end
i无视案例

更先进的:

 var isOk  = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test('#ac3') // for #f00 (Thanks Smamatti)
function isHexaColor(sNum){
  return (typeof sNum === "string") && sNum.length === 6 
         && ! isNaN( parseInt(sNum, 16) );
}

isHexaColor("AA33FF") => true
isHexaColor("Z34FF9") => false
isHexaColor("AA33FF11") => false

编辑 :请参阅下面@SalvadorDali的评论,在某些情况下有误报。 而是使用其他解决方案

这可能是一个复杂的问题。 经过几次尝试,我想出了一个相当干净的解决方案。 让the browswer为您完成工作。

步骤1:创建一个border-style设置为none的div。 div可以在屏幕外定位,也可以是页面上不使用边框的任何div。

第2步:将边框颜色设置为空字符串。 代码可能如下所示:

e=document.getElementbyId('mydiv');
e.style.borderColor="";

第3步:将边框颜色设置为您不确定的颜色。

e.style.borderColor=testcol;

第4步:检查颜色是否实际发生了变化。 如果testcol无效,则不会发生任何更改。

col2=e.style.borderColor;
if(col2.length==0) {alert("Bad Color!");}

步骤5:通过将颜色设置回空字符串来自行清理。

e.style.borderColor="";

分区:

<div id="mydiv" style="border-style:none; position:absolute; left:-9999px; top:-9999px;"></div>

现在JavaScript函数:

function GoodColor(color)
{
   var color2="";
   var result=true;
   var e=document.getElementById('mydiv');
   e.style.borderColor="";
   e.style.borderColor=color;
   color2=e.style.borderColor;
   if (color2.length==0){result=false;}
   e.style.borderColor="";
   return result;
}

在这种情况下,函数返回问题的真/假答案,另一个选项是让它返回有效的颜色值。 您的原始颜色值,borderColor中的值或空字符串代替无效颜色。

function validColor(color){
  var $div = $("<div>");
  $div.css("border", "1px solid "+color);
  return ($div.css("border-color")!="")
}

https://gist.github.com/dustinpoissant/22ce25c9e536bb2c5a2a363601ba261c

注意:这需要jQuery

这适用于所有颜色类型,而不仅仅是十六进制值。 它也不会追加到DOM树不必要的元素。

如果您需要一个函数来告诉您颜色是否有效,您可能会给它一些有用的东西 - 该颜色的计算值 - 并且当它不是有效颜色时返回null。 这是我对兼容(Chrome54和MSIE11)功能的抨击,以获得任何格式的“颜色”RGBA值 - 无论是'绿色',还是'#FFF','#89abcd',还是'rgb (0,0,128)',或'rgba(0,128,255,0.5)'。

/* getRGBA:
  Get the RGBA values of a color.
  If input is not a color, returns NULL, else returns an array of 4 values:
   red (0-255), green (0-255), blue (0-255), alpha (0-1)
*/
function getRGBA(value) {
  // get/create a 0 pixel element at the end of the document, to use to test properties against the client browser
  var e = document.getElementById('test_style_element');
  if (e == null) {
    e = document.createElement('span');
    e.id = 'test_style_element';
    e.style.width = 0;
    e.style.height = 0;
    e.style.borderWidth = 0;
    document.body.appendChild(e);
  }

  // use the browser to get the computed value of the input
  e.style.borderColor = '';
  e.style.borderColor = value;
  if (e.style.borderColor == '') return null;
  var computedStyle = window.getComputedStyle(e);
  var c
  if (typeof computedStyle.borderBottomColor != 'undefined') {
    // as always, MSIE has to make life difficult
    c = window.getComputedStyle(e).borderBottomColor;
  } else {
    c = window.getComputedStyle(e).borderColor;
  }
  var numbersAndCommas = c.replace(new RegExp('[^0-9.,]+','g'),'');
  var values = numbersAndCommas.split(',');
  for (var i = 0; i < values.length; i++)
    values[i] = Number(values[i]);
  if (values.length == 3) values.push(1);
  return values;
}

如果您尝试在HTML中使用它尝试直接使用此模式:

 pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$"

喜欢

<input id="hex" type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" />

它将进行验证以匹配所请求的格式。

添加长度检查以确保您没有误报

function isValidHex(testNum){
  let validHex = false;
  let numLength = testNum.length;
  let parsedNum = parseInt(testNum, 16);
  if(!isNan(parsedNum) && parsedNum.length===numLength){
     validHex = true;
  }
  return validHex;

}

我决定尝试不同的视角。 我的规则是:1) 任意长的十六进制字符序列,2) 在序列前面使用“0x”或“#”,或者 3) 只是一个十六进制数字或字符串。 我回想起 binhex 是大程序之一的时候。 Binhex 会创建非常大的文件,这些文件可以传输到任何地方,然后返回到您转换的任何文件中。 这些文件将有 80 个字符后跟一个回车符。 所以在这个函数中,我寻找回报并首先将它们取出。 修改了函数,使其同时查找 "\\n" 和 "\\r"。 这是代码:

////////////////////////////////////////////////////////////////////////////////
//  isHex(). Is this a hex string/value?
//  Arguments   :   0   =   Item to test
//                  1   =   V(alue) or S(tring). Default is STRING.
////////////////////////////////////////////////////////////////////////////////
function isHex()
{
    var p = 0;
    var re1 = /(\n|\r)+/g;
    var re2 = /[\Wg-zG-Z]/;
    var re3 = /v/i;
//
//  Make sure the string is really a string.
//
    var s = arguments[0];
    if( typeof s != "string" ){ s = s.toString(); }
//
//  Check if this is a hex VALUE
//  and NOT a hex STRING.
//
    var opt = arguments[1];
    if( re3.test(opt) && (s.length % 2 > 0) ){ return "false"; }
//
//  Remove any returns. BinHex files can be megabytes in length with 80
//  column information. So we have to remove all returns first.
//
    s.replace( re1, "" );
//
//  IF they send us something with the universal "0x" or the HTML "#" on the
//  front of it - we have to FIRST move where we look at the string.
//
    if( s.substr(0,1) == "#" ){ p = 1; }
        else if( s.substr(0,2).toLowerCase() == "0x" ){ p = 2; }

   if( re2.test(s.substr(p,s.length)) ){ return "false"; }

   return "true";
}

alert("HELLO There!");
alert(isHex("abcdef"));
alert(isHex("0x83464"));
alert(isHex("#273847"));
alert(isHex("This is a test"));
alert(isHex(0x5346));

我有意将返回值保留为字符串,但您所要做的就是删除双引号,然后该函数将只返回 TRUE 或 FALSE。

如果希望支持ARGB,则支持的十六进制数为3、4、6、8。

const isColor = (strColor) => {
  return /^#(([0-9A-Fa-f]{2}){3,4}|[0-9A-Fa-f]{3,4})$/.test(strColor)
}

请注意, {2}应位于{3,4}之前,以确保可以将7 位十六进制正确检查为false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM