programing

문자열이 유효한 16진수 색상 표현인지 확인하는 방법은 무엇입니까?

css3 2023. 9. 27. 18:05

문자열이 유효한 16진수 색상 표현인지 확인하는 방법은 무엇입니까?

예를 들어,

AA33FF==

Z34FF9)된 16함(Z상)

AA33FF11)된 16상음)

투명한 지원 없이:

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

투명한 지원을 통해:

/^#[0-9A-F]{6}[0-9a-f]{0,2}$/i.test('#AABBCC80')

자세한 설명:

^ ->
# ->허튼소리
[0-9A-F] ->와 A에서 F0에서 9까지의 A에까 F지의서
{6} -> 6번히에 나타납니다.
[0-9a-f]{0,2} ->arent)가에 추가(00..
$ ->
i ->대소문자를 무시하다

3자 HEX 코드(투명하게 지원되지 않음)를 지원해야 하는 경우 다음을 사용합니다.

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

여기서 한가지 다른 점은

 [0-9A-F]{6}

로 대체되었습니다.

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

이것은 정확히 6자를 맞추는 대신 정확히 3자를 맞추는 것이지만 1~2회만 일치한다는 것을 의미합니다..ABC그리고.AABBCC, 그러나 그렇지는ABCD

조합된 솔루션:

var reg=/^#([0-9a-f]{3}){1,2}$/i;
console.log(reg.test('#ABC')); //true
console.log(reg.test('#AABBCC')); //true

// 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

은 . 왜냐하면 대신에Number('0x' + hex)했습니다, parseInt(hex, 16).
parseInt()부터 radix합니다()16AA'로 시작하므로 'AAXCC'와 같은 문자열을 구문 분석할 수 있음을 의미합니다.

Number() 는 전체 , 는합니다.지금이다,Number() 변수를 에 접두사를 붙여 radix다의 수

다음은 설명을 위한 표입니다.

╭─────────────┬────────────┬────────┬───────────────────╮
│ 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')    │
╰─────────────┴────────────┴────────┴───────────────────╯

이것은 복잡한 문제가 될 수 있습니다.몇 번의 시도 끝에 저는 꽤 깨끗한 해결책을 생각해 냈습니다.그 일은 브라우저가 대신 하도록 하세요.

1단계: 테두리 스타일을 none으로 설정한 디바를 만듭니다.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>

이제 자바스크립트 기능:

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의 값 또는 잘못된 색상 대신 빈 문자열.

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})$" />

요청한 형식과 일치하는 유효성 검사를 제공합니다.

색상이 유효한지 여부를 알려주는 함수가 필요하다면 유용한 것을 제공하는 것이 좋습니다. 즉, 해당 색상의 계산값을 제공하고 유효한 색상이 아닐 경우 null을 반환하는 것이 좋습니다.다음은 '녹색', '#FFF', '#89abcd', 'rgb(0,0,128)', 'rgba(0,128,0.5)' 등의 형식으로 "색"의 RGBA 값을 얻을 수 있는 호환(Chrome54 & MSIE11) 함수입니다.

/* 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;
}
function validColor(color){
  var $div = $("<div>");
  $div.css("border", "1px solid "+color);
  return ($div.css("border-color")!="")
}

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

참고: jQuery가 필요합니다.

이것은 16진수 값뿐만 아니라 모든 색상 유형에 적용됩니다.또한 DOM 트리에 불필요한 요소를 추가하지 않습니다.

저는 좋은 검증을 작성하기 위해 양성음성 테스트를 작성하고, 검증 코드가 작동해야 할 기준선을 설정하고, 여기에 있는 몇 가지 좋은 답변과 저만의 논리를 혼합하여 다음과 같이 생각해 냈습니다.

/^#(([0-9A-Fa-f]{2}){3,4}|[0-9A-Fa-f]{3})$/.test(hex)

http://www.regexplained.co.uk

테스트 사례:

(사례의 90% 이상을 다루는 hopefully)

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

// positive tests
[
  '#ffffff',   // 6-characters, valid range
  '#ffffff99', // 9-characters, last 2 for alpha channel
  '#fff',      // 3-characters
].forEach(c => console.log(isValidHex(c), c));

console.log('\nshould fail:\n\n');

// negative tests
[
  '#invalid',   // obviously not a color
  '#f',         // 1 character is not enough
  '#ff',        // 2 characters is not enough
  '#ffff',      // 4 characters is not enough
  '#fffff',     // 5 characters is not enough
  '#fffffff',   // 7 characters is not enough
  '#ffffff999', // 9 characters are too many
  '#ggg',       // HEX is base 16, so characters beyond "F" (16) are invalid
].forEach(c => console.log(isValidHex(c), c))

거짓 양성이 나오지 않도록 길이 검사를 추가

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가 지원되는 경우 지원되는 16진수는 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자리 16진수가 false로 올바르게 확인될 수 있도록 합니다.

언급URL : https://stackoverflow.com/questions/8027423/how-to-check-if-a-string-is-a-valid-hex-color-representation