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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8027423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:26:20  来源:igfitidea点击:

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

javascriptjquerycolors

提问by Alex

For example:

例如:

AA33FF= valid hex color

AA33FF= 有效的十六进制颜色

Z34FF9= invalid hex color (has Z in it)

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

AA33FF11= invalid hex color (has extra characters)

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

回答by Royi Namir

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

To elaborate:

详细说明:

^ ->match beginning
# ->a hash
[0-9A-F] ->any integer from 0 to 9 and any letter from A to F
{6} ->the previous group appears exactly 6 times
$ ->match end
i ->ignore case

^ ->匹配开始
# ->的哈希
[0-9A-F] ->从0到9的任意整数,并从A至F的任何字母
{6} ->前一组恰好出现6次
$ ->匹配端
i ->忽略大小写

If you need support for 3-character HEX codes, use the following:

如果您需要支持 3 个字符的十六进制代码,请使用以下命令:

/^#([0-9A-F]{3}){1,2}$/i.test('#ABC')

The only difference here is that

这里唯一的区别是

 [0-9A-F]{6}

is replaced with

被替换为

([0-9A-F]{3}){1,2}

This means that instead of matching exactly 6 characters, it will match exactly 3 characters, but 1 or 2 times. Allowing ABCand AABBCC, but not ABCD

这意味着它不会精确匹配 6 个字符,而是精确匹配 3 个字符,但会匹配 1 或 2 次。允许ABCAABBCC,但不允许ABCD

回答by fflorent

// regular function
function isHexColor (hex) {
  return typeof hex === 'string'
      && hex.length === 6
      && !isNaN(Number('0x' + hex))
}

// or as arrow function (ES6+)
isHexColor = hex => typeof hex === 'string' && hex.length === 6 && !isNaN(Number('0x' + hex))

console.log(isHexColor('AABBCC'))   // true
console.log(isHexColor('AABBCC11')) // false
console.log(isHexColor('XXBBCC'))   // false
console.log(isHexColor('AAXXCC'))   // false

This answer used to throw false positives because instead of Number('0x' + hex), it used parseInt(hex, 16).
parseInt()will parse from the beginning of the string until it reaches a character that isn't included in the radix (16). This means it could parse strings like 'AAXXCC', because it starts with 'AA'.

这个答案曾经抛出误报,因为Number('0x' + hex)它使用了parseInt(hex, 16).
parseInt()将从字符串的开头开始解析,直到到达一个不包含在基数 ( 16)中的字符。这意味着它可以解析像“AAXXCC”这样的字符串,因为它以“AA”开头。

Number(), on the other hand, will only parse if the whole string matches the radix. Now, Number()doesn't take a radix parameter, but luckily, you can prefix number literals to get a number in other radii.

Number(),另一方面,只有在整个字符串与基数匹配时才会解析。现在,Number()不接受基数参数,但幸运的是,您可以为数字文字添加前缀以获取其他半径中的数字。

Here's a table for clarification:

这里有一张表供澄清:

╭─────────────┬────────────┬────────┬───────────────────╮
│ Radix       │ Characters │ Prefix │ Will output 27    │
╞═════════════╪════════════╪════════╪═══════════════════╡
│ Binary      │ 0-1        │ 0b     │ Number('0b11011') │
│ Octal       │ 0-7        │ 0o     │ Number('0o33')    │
│ Decimal     │ 0-9        │ -      │ -                 │
│ Hexadecimal │ 0-9A-F     │ 0x     │ Number('0x1b')    │
╰─────────────┴────────────┴────────┴───────────────────╯

回答by Terry Prothero

This can be a complicated problem. After several attempts I came up with a fairly clean solution. Let the browswer do the the work for you.

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

Step 1: Create a div with border-style set to none. The div can be positioned off screen or it can be any div on your page that doesn't use the borders.

第 1 步:创建一个边框样式设置为无的 div。div 可以位于屏幕外,也可以是页面上不使用边框的任何 div。

Step 2: Set the border color to an empty string. The code might look something like this:

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

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

Step 3: Set the border color to the color you aren't sure about.

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

e.style.borderColor=testcol;

Step 4: Check to see if the color actually got changed. If testcol is invalid, no change will occur.

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

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

Step 5: Clean up after yourself by setting the color back to an empty string.

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

e.style.borderColor="";

The Div:

部门:

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

Now the JavaScript function:

现在 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;
}

In this case, the function is returning a true/false answer to the question, the other option is to have it return a valid color value. Your original color value, the value from borderColor or an empty string in place of invalid colors.

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

回答by Mohit Dhawan

If you are trying to use it in HTML Try using this pattern Directly :

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

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

like

喜欢

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

It will give a validation to match the requested format.

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

回答by Dustin Poissant

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

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

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

Note: This requires jQuery

注意:这需要jQuery

This works for ALLcolor types not just hex values. It also does notappend unnecessary elements to the DOM tree.

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

回答by Abacus

If you need a function to tell you if a color is valid, you might as well have it give you something useful -- the computed values of that color -- and return null when it is not a valid color. Here's my stab at a compatible (Chrome54 & MSIE11) function to get the RGBA values of a "color" in any of the formats --be it 'green', or '#FFF', or '#89abcd', or 'rgb(0,0,128)', or 'rgba( 0, 128, 255, 0.5)'.

如果您需要一个函数来告诉您颜色是否有效,您不妨让它为您提供一些有用的东西——该颜色的计算值——并在它不是有效颜色时返回 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;
}

回答by rotato poti

Add a length check to make sure that you don't get a false positive

添加长度检查以确保您不会得到误报

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;

}

}