JavaScript - Examples

Random Color Example

Generate random color in hexadecimal

  function randomColor (){
    charset = "ABCDEF0123456789";
    hexColor = "";
    for (var i = 0; i < 6; i++) {
      hexColor = hexColor + charset.charAt(Math.floor(Math.random() * charset.length));
    }
    hexColor = "#" + hexColor;
    return hexColor;
  }

Even One Checker Example

Check if a binary string contains an even number of 1's (101011 - true ).

function evenOneChecker (binaryNumbar){
  var oneNumber = 0;
  for (i = 0; i < binaryNumbar.length; i++) {
    if (binaryNumbar.charAt(i)=='1'){
      oneNumber++;
    }
  }
  if(oneNumber%2==0){
    return true;      
  }
  return false;
}

Check if the string is Hexadecimal number

The function check if the string is contain only a valid Hexadecimal characters and return true or false.

function isHex(input) {
  for (i = 0; i < input.length; i++) {
    if (!(/[0-9A-F]/i.test(input.charAt(i)))){
      return false;
    }
  }
  return true;
}

Check if the string is Decimal number

The function check if the string is contain only a valid Decimal characters (digits only) and return true or false.

function isDecimal(input) {
  for (i = 0; i < input.length; i++) {
    if (!(/[0-9]/i.test(input.charAt(i)))){
      return false;
    }
  }
  return true;
}   

Check if the string is Binary number

The function check if the string is contain only a valid Binary characters (0 or 1) and return true or false.

function isBinary(input) {
  for (i = 0; i < input.length; i++) {
    if ((input.charAt(i)!='1')&&(input.charAt(i) !='0')){
      return false;
    }
  }
  return true;
}