Validate hexadecimal color without using RegEx - javascript

I am figuring out how to validate hexadecimal color ("#1234a6" and "#1cf") without using regExp. Can anyone please tell me why my code is not working properly
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;
Thank you.

No loop or charcodeat required
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
Let me break down the check = line into it's constituent parts
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)
To break down where your code went wrong
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;
}
}
to do the above loop correctly
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

Okay so here's a simple code snippet that does that correctly without loops etc.
You'll notice that I created a lambda function in there to deal with s starting with a #
This is to allow you to expand the notion to deal with specifications like rgb(1,2,3) and rgba(4, 5, 6, 1) etc.
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'));

You may directly parse the value to number and check against the base 10 integer value:
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;
}
}

Related

First Unique Character in a String Leetcode - using pointers (javascript)

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
leetcode question
"cc" // -1
"ccdd" // -1
"leetcode" // 1
"loveleetcode" // 2
"abcabd" // 2
"thedailybyte" // 1
"developer" // 0
My approach passed all the test cases except the 2nd test case "ccdd". I am expecting -1 but receiving 4. Not sure why.
var firstUniqChar = function(s) {
if(!s || s.length === 0 ) return -1
else if(s.length === 1) return 0
let pointer1 = 0
let pointer2 = pointer1 + 1
if(s.length > 2){
while(pointer2 <= s.length - 1){
if(s[pointer1] !== s[pointer2])
pointer2++
else if(s[pointer1] === s[pointer2])
pointer1++
}
return pointer1
}
return -1
};
this is too old, but still can be too much shorter:
const firstUniqChar = (_str) => {
for (let i= 0; i < _str.length; i+= 1) {
if (_str.indexOf(_str[i]) === _str.lastIndexOf(_str[i])) return i+1;
}
return -1;
}

Invalid parenthesis number and its position in a string

I am trying to find the number of invalid parentheses and its position. I have used an array to hold the invalid parenthesis position number. But myArray.pop() is not triggering.
function processData(input) {
var myArray = [];
var paranthesisIndex = 0;
for (C of input) {
paranthesisIndex++
if (C === '(') {
myArray.push(paranthesisIndex);
} else if (C === ')') {
if (myArray.length < 0 && myArray[myArray.length - 1] === '(') {
myArray.pop() //not working
} else {
myArray.push(paranthesisIndex)
}
}
}
console.log(myArray.length)
for (i = 0; i < myArray.length; i++) {
console.log(myArray[i])
}
}
processData("())()");
output
5
1
2
3
4
5
expected output
1
3
You used if( myArray.length<0 ... so your code never runs because the array should has no element in order to run if block. Maybe you wanted to use if( myArray.length> 0 ....

how to fix: Array index is out of range

i have this problem
Have the function WildcardCharacters(str) read str which will contain two strings separated by a space. The first string will consist of the following sets of characters: +, , and {N} which is optional. The plus (+) character represents a single alphabetic character, the asterisk () represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1. Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
i have the solution with js, but now i am trying to solve with swift, i need your help.
this work with js, and i'm using swift v4.2
code with js
function WildcardCharacters(str) {
// code goes here
let strArr= str.split(' ')
let specChar = strArr[0]
let charStr = strArr[1].split('')
let arr = specChar.split('')
let letters = /^[A-Za-z]+$/
let i = 0
while(i< arr.length){
if(arr[i] == '+'){
if(!charStr[0].match(letters)) return "false"
charStr = charStr.slice(1,charStr.length)
}
else if(arr[i] == '*'){
let curr = charStr[0]
let j = 1, k = 0
if(arr[i+1] != undefined && arr[i+1] == '{'){
k = arr[i+2]
i = i+4
}else{
k = 3
i++
}
while(j < k){
charStr = charStr.slice(1,charStr.length)
if(charStr[0] != curr) return "false"
j++
}
charStr = charStr.slice(1,charStr.length)
continue
}
i++
}
if(charStr.length != 0) return 'false'
return "true"
}
// keep this function call here
WildcardCharacters("+++++* abcdemmmmmm");
code by Smakar20 (user github)
code with swift
extension String {
func isAlphanumeric() -> Bool {
return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
}
func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
if ignoreDiacritics {
return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != ""
}
else {
return self.isAlphanumeric()
}
}
}
func wild (str: String) -> String
{
let strArr = str.split(separator: " ")
let specChar = strArr[0]
var charStr = Array(strArr[1])
let arr = Array(specChar)
var i = 0
while (i<arr.count)
{
if arr[i] == "+"
{
if !String(charStr[0]).isAlphanumeric()
{
return "false"
}
charStr = Array(charStr[0...charStr.count])
}
else if arr[i] == "*"
{
let curr = charStr[0]
var j = 0
var k = 0
if String(arr[i+1]).isAlphanumeric() != true && arr[i+1] == "{"
{
k = Int(String(arr[i+2]))!
i = i+4
}
else
{
k = 3
i += 1
}
while (j<k)
{
charStr = Array(charStr[1...charStr.count])
if charStr[0] != curr
{
return "false"
}
j += 1
}
charStr = Array(charStr[1...charStr.count])
continue
}
i += 1
}
if charStr.count != 0
{
return "false"
}
return "true"
}
wild(str: "+++++* abcdemmmmmm")
if str is "++*{5} gheeeee" then the second string in this case does match the pattern, so your program should return the string true. If the second string does not match the pattern your program should return the string false.
heeelp

in Java script Given two strings, find if they are one edit away from each other

can you help me to write a function in javascript to Given two strings, find if they are one edit away from each other example :
(pale, ple ) true
(pales, pale ) true
(pale, bale ) true
(pale, bake) false
(face, facts ) false
Can you try this function to check that string only differs by one edit.
function checkDifferntString(str1, str2) {
let diff = 0;
if (str1 === str2) return true; // equal return true
let lengthDiff = Math.abs(str1.length - str2.length)
if (lengthDiff > 1) return false; // checks length diff if > 2 return false
for (let i=0; (i<str1.length || i < str2.length);i++) {
if (diff > 1) return false; // diff greater than 1 return false
if (str1.charAt(i) !== str2.charAt(i)) diff++
}
if (diff <= 1) return true
else return false;
}
console.log(checkDifferntString("pale", "pale")) // true
console.log(checkDifferntString("pale", "pales")) // true
console.log(checkDifferntString("pales", "pale")) // true
console.log(checkDifferntString("pales", "bale")) // false
I hope it helps. Thanks!
Check this out.
I made a simple function that iterates through the given two strings and check if there's more than 1 difference (in terms of characters) between these strings, an optional argument cs to allow case sensitivity, by default it equals to false, so 'a' and 'A' are the same.
function isEditFrom(str1, str2, cs) {
var cs = cs || false, i = 0, diff = 2, len1 = str1.length, len2 = str2.length, l = (len1 > len2) ? len1: len2;
if(len1 !== 0 && len2 !== 0) {
if(cs === false) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
}
for(; i < l; i++) {
if(str1[i] !== str2[i]) {
if(--diff === 0) {
return false;
}
}
}
return true;
} else {
return false;
}
}
and now we call that function:
isEditFrom('Pale', 'bAle'); // returns True
isEditFrom('Pale', 'bAle', true); // returns False as we set the third argument to true enabling case sensitivity, 'a' != 'A'
isEditFrom('face', 'facts'); // returns False

Validate Credit card without regExp

I am trying to validate credit card number which may contain four tests of alphanumeric characters, separated by hyphens (-) or without hyphens. Not using regExp.
I have tried different ways but I can't figure out how to do it properly.
That's what I have done so far:
function isCredit(input) {
var i, code;
//if input.length > 19, stop execution
if(input.length > 19) return false;
for(i = 0; i < input.length; i++) {
code = input.charCodeAt(i);
//Matches to only numbers and Capital letters
if((code > 47 && code < 58) && (code > 64 && code < 91)) {
//if every 5th character is "-"
if((input.slice(4, 5) === "-") && (input.slice(9, 10) === "-") &&(input.slice(14, 15) === "-")) {
return true;
}
}
return false;
}
}
isCredit("12A4-56H8-43K6-36U3"); // returns true;
isCredit("4427A693CF324D14"); // returns true;
isCredit("----------------"); // returns false;
Any help and guidance appreciated!
I'm not exactly clear on your requirements. Here I'm assuming "12A556H8-43K636U3" is a valid card number if you allow hyphen omissions.
function isAlphaNum(ch) {
var code = ch.charCodeAt(0);
return ((code > 47 && code < 58) || (code > 64 && code < 91));
}
function isCard(str) {
var char, i = 0, x = [1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1];
while (char = str[i++]) {
if (x[0] == undefined) {
return false;
}
if (isAlphaNum(char)) {
if (x[0]) {
x.shift();
} else {
x.splice(0,2);
}
} else if (char == '-') {
if (!x[0]) {
x.shift();
} else {
return false;
}
} else {
return false;
}
}
return x[0] == undefined;
}

Categories