(This is not a duplicate. I can't find the solution in the link provided).
Say I have an input from a user in an html form intended as a serial number or some such. This number can start with 0s. Example, 0001.
In Javascript, if that number (0001) is incremented, it becomes 2.
I would like to preserve the leading 0s to get 0002.
How do I do that in Javasript?
Thanks in anticipation.
Use padStart to pad the start of a number. However numbers don't start with zero so the number will have to be displayed as a string.
To find the number of zeros, you can do:
('001'.match(/^0+/) || [''])[0].length
'001'.match(/^0+/) – matches as many zeros as possible from the start of the string
|| [''] – if the match returns undefined, use an array with an empty string (aka a fallback value)
[0] – get the first value in the returned array (either the match or the fallback)
.length – get the length of the string
let nums = [
'1',
'01',
'001',
'0001'
]
let str = ''
for (let i of nums) {
let numZeros = (i.match(/^0+/) || [''])[0].length
let num = Number(i)
while (num < 20) {
str += `<p>${String(num++).padStart(numZeros + 1, '0')}</p>`
}
}
document.body.innerHTML = str
Related
I'm trying to solve a problem: Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. I did the repetition of numbers, how next - I don’t know.
function explode(s) {
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
console.log(y);
}
}
You were only missing a result string to collect the parts
function explode(input) {
let result = '';
let s = input.toString(); // So that input can also be a number
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
result += y;
}
return result;
}
Javascript is good at coercing numbers to string and vice versa but I prefer to make clear when a numerical character is being treated as a number and when it is intended to be a string.
My snippet tests processing of numbers, string representations of numbers, strings having mixtures of number and letter characters, and letter strings.
it makes use of array.split() to for the character array, array.map() to process the characters (including parseInt to formally change the character to a number when used as the argument the string.repeat(), and array.join() to return the desired numeric string after processing:
let number = 6789;
let numberString = "12345";
let badNum = "3bad2Number";
let noNum = "justLetters";
console.log(expandNums(number));
console.log(expandNums(numberString));
console.log(expandNums(badNum));
console.log(expandNums(noNum));
function expandNums(numOrString) {
let numString = numOrString.toString();
let chars = numString.split('');
let processed = chars.map(char => char.repeat(parseInt(char)));
return processed.join('');
} // end function expandNums
The function performs well under all use situations tested, so is unlikely to throw an error if a bad argument is passes. It also does a good job with the mixed letter/number example.
I am working on a Chat bot for discord that has an addition calculator.... I am currently trying to find the .indexOf the first time a number appears in the string... For ex: !add 1 + 1 would be the command to add 1 and 1... I have an array that I use that contains all single numbers ex:
const singleNumbers = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
];
when I get the string back I am using
for (const num of singleNumbers){
const num1 = msg.content.indexOf(num,);
const add = '+';
const locationOfAdd = msg.content.indexOf(add,);
const num2 = msg.content.indexOf(num,locationOfAdd);
const add1 = msg.content.slice(num1,) * 1;
const add2 = msg.content.slice(num2,) * 1;
msg.reply(add1 + add2);
}
When I run this... It for some reason will only use the first number of the Array so the numbers I use in !add 1 + 1 have to start with 0... so !add 01 + 01 which in math is fine... but for simplicity how do I make it be able to start with any number in the array rather than the first... If you don't know discord.js,
msg.content
Is the string returned so if I type in chat...
Hey Guys what's goin on?
it would return as a String ("Hey Guys what's goin on?")...
To sum this all up... I am wondering how to make my const num that I declared in my for of loop check for all the numbers in its array rather than just the first in my case 0.
If you just want to find the index for the first digit str.search(/[0-9]/) or str.match/[0-9]/).index.
Using regex to extract the numbers, and reduce to add them:
match on: string starts with !add, at least one space, at least one digit as a capture group, optional space and a + sign, another series of digits as a capture group.
You get an array with [full match, digit group 1, digit group 2]. I slice off the full match, and then use reduce to (+x converts the string to a number; you could also use Number(x)) to add each number and collect it in sum.
const sum = msg.content.match(/^!add\s+(\d+)\s*\+\s*(\d+)/).slice(1).reduce((sum,x)=>+x+sum,0)
Note: \d is the same as [0-9]
JavaScript.info RegExp tutorial
I run:
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
And I get an array like:
["27","-","28","August","663","CE"]
How would I iterate with that array and loop it to find if an object is a text string or a number?
To be perfectly correct, these are all of the type string, because they are between quotes. I guess you want to find out if these strings can be converted to a number. You can check this with isNan(), gives false when numeric and true when not. You can actually convert the string to a number (integer) with parseInt();
var array = ["27","-","28","August","663","CE"];
for (var el of array) {
if(!isNaN(el)) { // check if el is numeric
el = parseInt(el); // parse el to a int
console.log("This element is numeric");
console.log(el);
}
}
You can use the jQuery $.isNumeric() inside a $.each loop
$.each(words,function(){
if($.isNumeric(this)) {
//code to execute if number
}
})
You can use Number(), which returns NaN if string is non-numeric. One thing to keep in mind is that Number('') === 0.
for (const word of words.split(' ')) {
if (isNaN(Number(word)) {
//code if non-numeric
}
else {
//code if numeric
}
}
you can use Number() directly
var arr = ["0","-","28","August","663","CE"]
function isNumber(str) {
return str && isNaN(Number(str)) ? false : true
}
arr.forEach((item) => {
console.log(isNumber(item))
})
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
console.log(/\d+/g.test(words[i])); // RegExp way (possible only with input formatted like string you specified)
console.log(/^[\d]+(.[\d]+)*$/g.text(words[i])); // RegExp way that would consider floats, ints as a number and would not consider strings like "123aaa" as a number
console.log(!isNaN(parseInt(words[i]))); // NaN with parseInt way
console.log(!isNaN(words[i])); // only NaN way - warning: strings like "123aaa" are considered as a number as parseInt would create an int
with vale of 123
console.log(!isNan(Number(words[i])) && words[i] !== ''); // csadner's solution with Number
// all above logs will output true if the string is a number
}
This should probably solve the problem. What's going on here is:
Regular expression checks if provided string contains only the numbers
parseInt will return NaN (Not a Number) on fail, so we check if the returned value is not NaN.
isNaN itself checks if string is a number - in case you don't want to have hexadecimals, etc.
In the for loop you already have, you can determine if it's NOT a number with this condition:
!words[i] || isNaN(words[i])
If that is true, it's not a number
I have a requirement to check if some given numbers are Pythogorean triplets.
The textbox accepts string of numbers in the below format:
3,4,5 (comma separated values)
If the user enters more than or three numbers an error alert is displayed. My team mate figure out a way to do this , but accidentally. How does the below method work?
function CheckNumbers(strnum){
var num = strnum.split(",")
if(num.length != 3)
{
alert(Enter exactly three numbers!)
return;
}
}
Should'nt it return the length of the string rather than the number of numbers?
As I read it, the input parameter strnum gets split by "," into an array, and num.length returns the length of the array.
No, The above code is right what it does is to break string in to an array and than return the length of that array
strnum = 1,2,3;
num = strnum.split(",") // num = [1,2,3]
num.length // 3
Your case is you are using a Number, and replace is associated to String.
Try to cast it before.
strnum = "1,2,3";
num = strnum.split(",") // num = [1,2,3]
num.length // 3
var result ="1fg";
for(i =0; i < result.length; i++){
var chr = result.charAt(i);
var hexval = chr.charCodeAt(chr)
document.write(hexval + " ");
}
This gives NaN 102 103.
Probably because it's treating the "1" as a integer or something like that. Is there a way I can convert the
"1"->string to the correct integer? In this case: 49.
So it will be
49 102 103 instead of NaN 102 103
Cheers,
Timo
The charCodeAt function takes an index, not a string.
When you pass it a string, it will try to convert the string to a number, and use 0 if it couldn't.
Your first iteration calls '1'.charCodeAt('1'). It will parse '1' as a number and try to get the second character code in the string. Since the string only has one character, that's NaN.
Your second iteration calls 'f'.charCodeAt('f'). Since 'f' cannot be parsed as a number, it will be interpreted as 0, which will give you the first character code.
You should write var hexval = result.charCodeAt(i) to get the character code at the given position in the original string.
You can also write var hexval = chr.charCodeAt(0) to get the character code of the single character in the chr string.