不使用RegEx

时间:2017-11-01 05:04:22

标签: javascript

我在不使用regExp的情况下弄清楚如何验证十六进制颜色(“#1234a6”和“#1cf”)。任何人都可以告诉我为什么我的代码不能正常工作

function checkHex(input) 
{
    var i, code, len;
    // If first letter isn't "#" stop executing
    if(input.charAt(0) !== "#") return false;
     code = input.charCodeAt(i);
      for(i = 1; len = input.length, i < len; i++) {
        if(len == 3 || len == 6 ) {
          if((code > 47 && code < 58) && (code > 96 && code < 103)) {
            return true;
          }
        }
        return false;
      }
}
checkHex("#1234a6"); // returns false; which should be true;

谢谢。

3 个答案:

答案 0 :(得分:3)

不需要循环或charcodeat

function checkHex(input) {
    var check, code, len;
    if(typeof input == 'string') {        // check it's a string
        if(input[0] === "#") {            // and it starts with #
            len = input.length;
            // if (len === 4 || len === 7 || len == 5 || len == 9) { // 5 and 9 for #RGBA and #RRGGBBAA
            if (len === 4 || len === 7) { // and it's 4 or 7 characters
                input = input.toLowerCase(); // convert to lower case
                // parse it as hex and output as hex with # prefix
                check = '#' + ('00000000' + parseInt(input.substr(1), 16).toString(16)).substr(1 - len);
                // check it's the same number
                return check === input;
            }
        }
    }
    // all other conditions fall thru to here
    return false;
}
console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true

让我将check =行分解为其组成部分

check = '#' +                       // start with a '#'
('00000000' +                       // some leading zeros for profit
    parseInt(input.substr(1), 16)   // parse the text as a HEX integer - that's the 16 argument
    .toString(16)                   // now, back to a string, in HEX, again 16 argument does that
).substr(1 - len);                  // we take the last (len-1) characters to match the input length less 1 (the # is the first line)

分解代码出错的地方

function checkHex(input) {
    var i, code, len;
    // If first letter isn't "#" stop executing
    if(input.charAt(0) !== "#") return false;
     // next line should be inside the loop
    code = input.charCodeAt(i);
    for(i = 1; len = input.length, i < len; i++) {
        // you should check for length being 4 or 7, and this check should be outside the loop
        if(len == 3 || len == 6 ) {
            // a value can not be between 47 and 48 AND between 96 and 103 - so this is never true
            if((code > 47 && code < 58) && (code > 96 && code < 103)) {
                // returning in a for loop exits the function, so even fixing all of the above this would return true if the first digit was valid
                return true;
            }
        }
        return false;
    }
}

正确执行上述循环

function checkHex(input) {
    var i, code, len;

    if (input[0] === "#") {
        len = input.length
        if (len == 4 || len == 7 ) {
            input = input.toLowerCase(); // rgb hex values are valid in either upper or lower case
            for(i = 1; i < len; i++) {
                code = input.charCodeAt(i);
                // note the ! and the || in the next line
                // we want to check that the digit is NOT in 0123456789 OR abcdef
                if (!((code > 47 && code < 58) || (code > 96 && code < 103))) {
                    return false; // not a hex digit, so return false
              }
            }
            //loop has made it all the way through, so it's correct
            return true;
        }
    }
    return false;
}

console.log(checkHex("#1234a6")); // true
console.log(checkHex("1234a6")); // false
console.log(checkHex("#1234")); // false
console.log(checkHex("#12345t")); // false
console.log(checkHex("#aBc")); // true
console.log(checkHex("#000")); // true
console.log(checkHex("#00001")); // false
console.log(checkHex("#000001")); // true

答案 1 :(得分:0)

好的,这是一个简单的代码片段,无需循环等即可正确完成。

您会注意到我在那里创建了一个lambda函数来处理s

开头

这是为了让您扩展处理rgb(1,2,3)rgba(4, 5, 6, 1)等规范的概念。

    isRGB = function(s) {
    
           if(typeof(s) !== "string") 
               return false;
    
           if(s[0] === '#') 
             return (function(hexStr) {
                if(hexStr.length != 3 && hexStr.length != 6)
                   return false;
                return !isNaN(Number("0x" + hexStr));                  
             })(s.substr(1));
           
           return false;
    }
    

    console.log(isRGB('#01a5'));
    console.log(isRGB('#0a5'));
    console.log(isRGB('#0a5029'));

答案 2 :(得分:-1)

您可以直接将值解析为数字,并检查基数为10的整数值:

function checkHex(input) {
    /*
      1193126 = 0x1234a6
      463 = 0x1cf
      1166591 = 0x11ccff
    */
    if(input.charAt(0) == '#') {
        var intNumber = Number(input.replace("#","0x"));
        return isNaN(intNumber) ? false : (intNumber == 1193126 || intNumber == 463 || intNumber == 1166591);
    } else {
        return false;
    }
}