I have a code below that matches a remainder of an 8 digit number to a letter when divided by 23.
function dniLetter( dni ) {
var lockup = 'TRWAGMYFPDXBNJZSQVHLCKE'
var result = '';
var remainder = dni % 23;
result = lockup.charAt(remainder)
return result; }
How could I improve if the number starts with a negative number (like -2) or start with a letter (A1234567)?
For the negative numbers, you should try replacing dni % 23 by ((dni % 23) + 23) % 23. It will do exactly what you want.
You should use regular expressions.
/^[a-zA-Z-]/.test(yourString) returns true on the specified conditions (and even if it starts with '-A' for instance).
Related
I have an alphanumeric string, so I want to mask all the numbers in this string when the count of digits reaches 10. In this example, the digit count has reached the count of 10 two times irrespective of how many space, special character,s or digits are there
For ex:
string 1:- abc23 56 dfg %#34567fhgh0 1234567890 abc345
Output:- abc** ** dfg %#*****fhgh* ********** abc345
It ignores the characters and mask the number when the digit length reaches 10. I want to do this with regex. How can I do that?
You may use something like this:
if ((s.match(/\d/g) || []).length >= 10) {
s = s.replace(/\d/g, '*');
}
This will count the number of digit matches. If there are 10 or more digits, it replaces each one with a '*' character. If you want to only replace the digits if the string contains at least one set of 10 consecutive digits, see the end of the answer.
Here's a complete example:
var arr = ['abc23 56 dfg %#34567fhgh0 1234567890 abc345', 'abc123def'];
for (var i = 0; i < arr.length; i++) {
let s = arr[i];
if ((s.match(/\d/g) || []).length >= 10) {
s = s.replace(/\d/g, '*');
arr[i] = s;
}
console.log(s);
}
Output:
abc** ** dfg %#*****fhgh* ********** abc***
abc123def
If you want the condition to be for 10 consecutive digits, use the following instead:
if (/\d{10}/g.test(s)) {
s = s.replace(/\d/g, '*');
}
You could split() the string into an array, check the length of the string, if it is over 10, then map the mask character where the number was using splice and its key along with Number and isNan.
var str = 'abc23 56 dfg %#34567fhgh0 1234567890'
var str2 = 'abc345'
var str3 = '%#34567fhg7'
var str4 = '1234567890'
const exchange = (str, cap) => {
// split the string and define array
const arr = str.split('')
// condtional to see if string.length is greater than cap
if (str.length > cap) {
// we have a string longer than cap, loop over the array, exclude
// empty spaces and check if value is a number using isNaN, if it is,
// we splice its value using the key with the mask character x
arr.map((char, k) => char !== ' ' ? Number.isNaN(Number(char)) ? null : arr.splice(k, 1, 'x') : null)
// return the value as a string by joining the array values together
return arr.join('')
} else {
// return the string as its length is not more than cap
return str
}
}
console.log(`${exchange(str, 10)}, length = ${str.length}`)
console.log(`${exchange(str2, 10)}, length = ${str2.length}`)
console.log(`${exchange(str3, 10)}, length = ${str3.length}`)
console.log(`${exchange(str4, 10)}, length = ${str4.length}`)
I'm looking for a solution to my problem
if I have numbers
var first = 14:1
var next = 13:8
therefore, the console should give a result
console.log(first_result) // 141
console.log(next_result) // 141
and I want the numbers counted like 141 in the result to be
simply if there is an example
13:8 if both digits are the last, 3 and 8 are bigger than ten, then turn the tens and turn and insert into the previous number and leave the rest at the end
so 13:8 becomes 141
If you are starting with strings, then you just simply split the string on : to get your 2 numbers.
To get the last digit, you can simply use x % 10. Then just add the numbers and see what happens.
let value = '13:8',
nums = value.split(':').map(Number),
last_digits = nums.map(x => x % 10),
// or last_digits.reduce((x,y) => x+y, 0)
sum = last_digits[0] + last_digits[1],
result;
if (sum > 10) {
nums[0]++;
nums[1] = sum - 10; // or, probably sum % 10
}
result = nums.join('');
console.log(result);
So I have a number like 5467. I want my code to return 546.
I tried taking the last number and subtracting it from the original number but I get 5460 instead of 546.
Combine / with %:
(5467 - (5467 % 10)) / 10
564
Sounds like you also need to divide my 10. You could do something like this:
var number = 5467;
number = number - (number % 10); // This will subtract off the last digit.
number = number / 10;
console.log(number); // 546
We first use the modulo operator % to get the last digit, and we subtract it from number. That reduces the number from 5467 to 5460. Now to chop off the last digit (which is guaranteed to be a 0) we divide by 10 and get 546.
Written more concisely you could do:
number = (number - ( number % 10)) / 10;
There's a few things you can do the most concise being:
Math.floor(num / 10);
Or, convert to a string, remove the last character and convert back to number.
parseInt(num.toString().slice(0, -1));
If string representation would be fine for you then one other way is
var num = 5467,
cut = (num/10).toFixed(); // <-'547'
Well... warning..! i have to say toFixed() method rounds if necessary. So in this particular example it doesn't work.
I dont mind some of the other answers, but i feel that this maybe too fixed on it being a number.
Which it is, but you want to remove the last digit/char, regardless of the number, so why not substr?
http://www.w3schools.com/jsref/jsref_substr.asp
var s = 5467;
s = s.toString().substr(0, s.toString().length - 1);
console.log(s)
or even easier:
var s = (5467).toString();
s = s.substr(0, s.length - 1);
console.log(s)
These dont take into account single digit numbers, so passing in 1 would return blank. To answer that you could simply do a check like:
var s = (1).toString();
if(s.length > 1)
s = s.substr(0, s.length - 1);
console.log(s)
Also, similar question to:
Remove last digits from an int
Remove the last digits of a number (not string)
Removing the last digits in string
To truncate digits from the right hand side until the number is less than 30, keep dividing by 10 and rounding down until a suitable value is reached:
var n = 12341235;
while (n > 30) n = n/10|0;
document.write(n);
The greater than and division operations will coerce n to a number, so it can be a number or string. If ToNumber(n) results in NaN (e.g. n = 'foo'), then the value of n is not modified.
You can simply divide the number by 10 and parseInt()
var num = 5467;
num = parseInt(num/10);
Update :
To repeat the process until the answer is less than 30, use while loop as
var num = 5467;
while(num >= 30) {
num = parseInt(num/10);
}
document.write(num);
e.g.,
var myNum = 1.208452
I need to get the last digit of myNum after decimal so it is (2)
You could try something like:
var temp = myNum.toString();
var lastNum = parseInt(temp[temp.length - 1]); // it's 2
Edit
You might want to check if your number is an actual decimal, you can do:
var temp = myNum.toString();
if(/\d+(\.\d+)?/.test(temp)) {
var lastNum = parseInt(temp[temp.length - 1]);
// do the rest
}
This approach:
var regexp = /\..*(\d)$/;
var matches = "123.456".match(reg);
if (!matches) { alert ("no decimal point or following digits"); }
else alert(matches[1]);
How this works:
\. : matches decimal point
.* : matches anything following decimal point
(\d) : matches digit, and captures it
$ : matches end of string
As pointed out in comments, I initially misunderstood your question and thought you wanted the FIRST digit after the decimal place, which is what this one-liner does:
result = Math.floor((myNum - Math.floor(myNum)) * 10);
If you want a purely mathematical solution that gives you the LAST digit after the decimal place you can transform the number until the last digit is the first one after the decimal place and THEN use the above code, like this (but it's no longer a nice one-liner):
temp = myNum;
while( Math.floor(temp) != temp ) temp *= 10;
temp /= 10;
result = Math.floor((temp- Math.floor(temp)) * 10);
How it works:
the above code multiplies temp by 10 until there is nothing after the decimal place, then divides by 10 to yield a number with only a single digit after the decimal place then uses my original code to give you the first digit after the decimal place! Phew!
Just do:
function lastdigit(a)
{
return a % 10;
}
I have a working decimal to binary converter, but I want it to ALWAYS show 8 digits,
so if I put in 3 it will say '00000011' and not '11'
Anyone a clue how this can be done?
my code:
<script type="text/javascript">
function ConvertToBinary(dec) {
var bits = [];
var dividend = dec;
var remainder = 0;
while (dividend >= 2) {
remainder = dividend % 2;
bits.push(remainder);
dividend = (dividend - remainder) / 2;
}
bits.push(dividend);
bits.reverse();
return bits.join("");
}
<input type="text" id="txtDec" maxlength="3"/>
<input type="button" value="Convert" onclick="document.getElementById('spBin').innerHTML=ConvertToBinary(document.getElementById('txtDec').value);" />
<span id="spBin"></span>
JavaScript already makes the conversion for you, from a number, using toString method, because you can specify the radix (see the link above):
var n = 13;
console.log(n.toString(2)) // "1101"
If you want add lead zero, in case less then 8, you could have:
var bits = n.toString(2);
console.log("00000000".substr(bits.length) + bits);
With just one method call.
Edit: this answer was written in 2013, nowadays the method padStart can be used instead for the padding:
console.log(n.toString(2).padStart(8, "0"));
How about this:
return String('000000000' + bits.join("")).slice(-8);
Demo (change "dividend" to try with different numbers)
Basically adds 8 zeros to the left and then removes anything more than 8 characters long from the left.
How about before bits.reverse(); You do a while loop like this:
while(bits.length < 8){
bits.push(0);
}
Here's an example solution that will left-pad a number with zeros
#param "num" the number to be left-padded with zeros
#param "width" the number of characters required as a result
#return String the left-padded number
function zeroFill(num, width) {
str = String((new Array(width+1)).join('0') + num).slice(-width)
return str
}
There are other solutions which use a loop to create the zeros.