I'm trying to make binary to decimal converter.
I want to cut input to 8 digits and allow only 0s and 1s with JavaScript functions.
The first test works, but I did not succeed yet in detecting inputs that have some other character than only 0s and 1s. How can I achieve that?
This is what I've tried so far:
function bin2dec() {
var bin = document.getElementById("input").value;
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (bin > 2) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = parseInt(bin, 2);
}
}
Testing bin > 2 is not helpful. You could use a regular expression to check if the input contains any characters other than 0 and 1.
if(/[^01]/.test(bin)){
//not binary
}
function bin2dec() {
var bin = document.getElementById("input").value;
document.getElementById("alert").innerHTML = "";
document.getElementById("output").innerHTML = "";
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (/[^01]/.test(bin)) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = parseInt(bin, 2);
}
}
document.querySelector("button").addEventListener("click", ()=>bin2dec());
<input id="input">
<button>Convert</button>
<p id="output"></p>
<p id="alert" style="color: red;"></p>
I suppose your question is about fixing this part:
else if (bin > 2) {
This condition would be true for the following inputs (remember the input is a string):
"30000000"
"98765432"
which is indeed what you want,... but it would not be true for all of the following, while it should:
"20000000"
"12345678"
"09999999"
To check that a string only consists of "0" or "1" you could use a regular expression:
if (/[^01]/.test(bin)) {
This [^01] means "a character that is neither '0' nor '1'". The test method will return true when a match is found, i.e. if there is such a character in bin that is not "0" nor "1".
bin > 2 only checks if the input is a decimal number and if it's less than 2. I don't think that's what you want. Try something like this:
function bin2dec() {
var bin = document.getElementById("input").value,
num;
if (bin.length > 8) {
document.getElementById("alert").innerHTML = "8 digits";
} else if (isNaN(num = parseInt(bin, 2))) {
document.getElementById("alert").innerHTML = "Enter binary value";
} else {
document.getElementById("output").innerHTML = num;
}
}
Explanation: isNaN(num = parseInt(bin, 2)) assigns the parsed value to num and if it's invalid (NaN), says "Enter binary value", otherwise continues to the else statement.
Related
I used random function, to generate a 4 digit number.
The generated 4 digit random number should not be in the sequence of 1111, 2222, 3333, .... The generated random number could be of any number except 1111, 2222, 3333, 4444,..
I used the below approach,
But, i could get the repeating of digits using the below code. Could somebody please help.
function repeatingDigit(n) {
let num = n.toString();
for (var i = 0; i <= num.length; i++) {
if (num.substr(i) == num.substr(++i)) {
alert('This pattern can not be used');
}
else {
return parseInt(n);
}
}
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
Thank you.
You could just check if it's divisible by 1111:
function repeatingDigit(n) {
if (n % 1111 === 0) {
alert('This pattern can not be used');
}
return n;
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
You can use a regular expression to test for that:
function repeatingDigit(n) {
let num = n.toString();
if (/(\d)\1{3}/.test(num)) {
alert('This pattern can not be used');
} else {
return parseInt(n);
}
}
repeatingDigit(Math.floor(1000 + Math.random() * 9000));
The regular expression /(\d)\1{3}/ tests for digits \d and checks if the following three characters are the same as the first found digit.
You can also use every() function which is inbuilt function provided by javascript to check wheather number is repeated or not after splitting number to array.
function repeatingDigit(num) {
var arr = String(num).split('');
if(arr.every(function (digit) { return digit === arr[0]}))
return 'Repeated Number!!';
else
return num;
}
console.log(repeatingDigit(Math.floor(1000 + Math.random() * 9000)))
Hope This Answer Will Help You! Happy Coding :)
I have a input field for a phonenumber.
Now i want to check with jquery/javascript the syntax and the characters of the number
I only accept this format: 31-123456789 (also more groupes seperated by - will be ok)
Its important to check if there is the international code at first.
I think about to do a kind of replace for replace "()/.:;" characters and check if the first letter is a 0.
But this looks for large code, also there is not check if the user has enter disallowed characters for example Abc...
How i can check and format the following examples in the easiest way?
031(123)123 -> should return 31-123-123
(0123)123 -> should return a error (no international code)
031.123 -> should return a error (no international code)
31.(123)123 -> 31-123-123
+31.123.123 -> 31-123-123
+31 (123) 123 -> 31-123-123
etc.
Thanks for showing and explaing me the way to do it.
Here is a try, that you could build on. It also fill all your requirement.
Now you can simply add your configration to internationalCodes and the method will do its job
// All valid internationl code
var internationalCodes= [
{ codes:["031", "0031", "31"], translateTo: "31", minLength: 8 }
]
var seperatorCount =3;
var seperator = "-";
function getNumber(num){
var notValid = num + " not valid";
num = num.trim().replace(/[^0-9]/g, ""); // replace all none number char
// find the international configration settings
var r = internationalCodes.filter(x=>
x.codes.findIndex(i=> num.substr(0, i.length)== i) != -1)
if (r.length<=0) // no internationalCodes configration
return notValid;
r = r[0];
if (num.length<r.minLength)
return notValid;
var resultNum = r.translateTo;
var code = r.codes.filter(x=> num.substr(0, x.length) == x)[0]
num = num.substr(code.length, num.lengt)
for (var i = 0; i< num.length; i++)
{
if (i % seperatorCount == 0)
resultNum += seperator;
resultNum += num[i];
}
return resultNum;
}
console.log(getNumber("031(123)123"))
console.log(getNumber("(0123)123"))
console.log(getNumber("031.123"))
console.log(getNumber("31.(123)123"))
console.log(getNumber("+31.123.123"))
console.log(getNumber("+31 (123) 123"))
console.log(getNumber("+50 (123) 123"))
Hi can somebody tell me why the output to my function defaults to even when you insert over 17 numbers? It's probably super simple, please go easy on me!
function oddOrEven(number) {
var number = document.getElementById('number').value;
if(number % 2 != 0) {
document.getElementById('demo').innerHTML = "Odd";
}
else {
document.getElementById('demo').innerHTML = "Even";
}
if (number.length === 0) {
document.getElementById('demo').innerHTML = "Odd / Even";
}
}
You can simplify this whole thing. If you are always grabbing the input with id 'number' you don't need to pass a param, and then after a simple test you can inline the answer you want:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
document.getElementById('demo').innerHTML = (number % 2) ? "Even" : "Odd";
}
}
All that said, I just caught that you're talking about 17 digits (thanks to #JJJ's comment) rather than using the function more than once. The problem in this case is that JS integers have a size limit. If you parse anything larger it returns a number you're not going to expect. There are a lot of discussion of general handling of very large numbers here: http://2ality.com/2012/07/large-integers.html, but for your modulus problem you could take the last digit and check if that's odd or even like so:
function oddOrEven(){
var val = document.getElementById('number').value;
var number = parseInt(val, 10);
// if it's not a valid number, you'll have NaN here which is falsy
if (number) {
var lastDigit = val[val.length-1];
document.getElementById('demo').innerHTML = (parseInt(lastDigit, 10) % 2) ? "Even" : "Odd";
}
}
I am trying to validate a phone number with javascript and I'm stuck at this part
The area code (first 3 numbers in 999) can't be all zeros (0)'s
I know the code to make which ever format i want (say xxx-xxx-xxxx) but how do I make sure the first 0 arent all zeroes?
any help is appreciated, thank you!!
You can do this in many ways, here's a few examples using different methods.
Using startsWith
var num = "000-xxx-xxxx";
if (num.startsWith("000") === true) {
console.log("Number starts with 000");
}
Using substr
var num = "000-xxx-xxxx";
var first_three = num.substr(0, 3);
if (first_three === "000") {
console.log("Number starts with 000");
}
Using split
var num = "000-xxx-xxxx";
var first_three = num.split("-")[0];
if (first_three === "000") {
console.log("Number starts with 000");
}
Using a regular expression
var num = "000-xxx-xxxx";
if (/^000/.test(num)) {
console.log("Number starts with 000");
}
You can use parseInt, it will ignore everything after the first non-numeric character in the string:
var phone1 = '000-555-4444';
var phone2 = '555-555-5555';
function isValidAreaCode(phoneNumber) {
return parseInt(phoneNumber, 10) > 0;
}
console.log(phone1, 'valid?', isValidAreaCode(phone1));
console.log(phone2, 'valid?', isValidAreaCode(phone2));
You can use ^[0]{3}$ or ^\d{3}$
Assuming you are testing American area codes, using the regular expression
/^[2-9][0-8][0-9]/ to test them should work. According to
this.
Areacodes can start with a number between 2 and 9, the second number can be any
number except 9 and the last number can be any number.
function hasValidAreaCode(num) {
var stripped = num.replace(/\D/g, ''); // remove any no-numeric characters
return /^[2-9][0-8][0-9]/.test(stripped);
}
Interactive example:
function hasValidAreaCode(num) {
var stripped = num.replace(/\D/g, ''); // remove any no-numeric characters
return /^[2-9][0-8][0-9]/.test(stripped);
}
var elPhonenumber = document.getElementById('phonenumber');
elPhonenumber.addEventListener('keyup', function (event) {
var v = elPhonenumber.value;
if (v.replace(/\D/g, '').length > 2) {
var valid = hasValidAreaCode(v);
if (valid) {
elPhonenumber.classList.add('valid');
elPhonenumber.classList.remove('invalid');
} else {
elPhonenumber.classList.remove('valid');
elPhonenumber.classList.add('invalid');
}
} else {
elPhonenumber.classList.remove('valid', 'invalid');
}
});
.valid, .invalid {
color: #000;
}
.valid {
color: green;
}
.invalid {
color: red;
}
<label for="phonenumber">Please enter a phonenumber</label> <input id="phonenumber">
I am trying to create a alphanumeric serial number in Javascript, the serial number is governed by the following rules:
3-Digit Alphanumeric Series
Allowed values 1-9 (Zero is excluded) and A-Z (All Capitals with exclusions of I and O)
The code should be able to give the next number after getting the input number.
The last part is tricky, basically the code would fetch the existing value of the serial number and it would then give the output as the next number.
For example: If the input number 11D then the output number should be 11E. Please let me know if this description is good enough to explain my requirement.
The excel sheet for the same is attached here
Also the part of the code where the script would fetch the starting value 11D would be from this code:
cur_frm.add_fetch('item_group','serial_number','serial_number');
This should do it:
var nextSerialNumber = function(serialNumber) {
return (parseInt(serialNumber, 36) + 1).toString(36).replace(
/i/g,'j').replace(/o/g, 'p').replace(/0/g, '1').toUpperCase();
}
nextSerialNumber("99Z") //=> "9A1"
nextSerialNumber("11D") //=> "11E"
I'm not sure what you want to happen after ZZZ. It jumps to 1111, but that could be changed.
If you input an invalid serial number (e.g. 11I), it gives you the next valid number (e.g. 11J).
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var alphabetLen = alphabet.length;
function nextDigit(digit) {
nextDigitPos = (alphabet.indexOf(digit)+1) % alphabetLen;
return alphabet.charAt(nextDigitPos);
}
/**
* Computes the next serial id.
* #param id the id to compute the successor of,
* if null or empty String the first id
* "111" is returned.
*/
function nextSerial(id) {
if(id==null || id.length==0) return "111";
var digits = id.split("");
digits[2] = nextDigit(digits[2]);
if(digits[2] == "1") /* overflow */ {
digits[1] = nextDigit(digits[1]);
if(digits[1] == "1") /* overflow */ {
digits[0] = nextDigit(digits[0])
}
}
return digits.join("");
}
This should do it:
function getNext(num) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var digits = num.toUpperCase().split(""),
len = digits.length,
increase = true;
if (len != 3)
throw new Error("Invalid serial number length in getNext: "+num);
for (var i=len-1; increase && i>=0; i--) {
var val = alphabet.indexOf(digits[i]);
if (val == -1)
throw new Error("Invalid serial number digit in getNext: "+num);
val++;
if (val < alphabet.length) {
digits[i] = alphabet[val];
increase = false;
} else { // overflow
digits[i] = alphabet[0];
}
}
if (increase) // is still true
throw new Error("Serial number overflow in getNext");
num = digits.join("");
return num;
}
Since you are working with a nearly alphanumeric alphabet, a parseInt/toString with radix 33 might have done it as well. Only you need to "jump" over the 0, I and O, that means replacing 0,A,B… by A,B,C…, replacing H,I,J… by J,K,L… and replacing M,N,O… by P,Q,R… (and everything back on deserialisation) - which might be OK if JS has a numeric char datatype, but I think it's easier to do it manually as above.
If you're curious:
String.prototype.padLeft = function(n, x) {
return (new Array(n).join(x || "0")+this).slice(-n);
};
function getNext(num) {
var alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
var back = {}, forth = {};
for (var i=0; i<alphabet.length; i++) {
var a = alphabet[i],
b = i.toString(36);
back[a] = b;
forth[b] = a;
}
return (parseInt(num.replace(/./g, function(c) {
return back[c]; // base33 from alphabet
}), alphabet.length) + 1)
.toString(alphabet.length)
.padLeft(3)
.replace(/./g, function(c) {
return forth[c]; // base33 to alphabet
});
}