How can I prefix and zeropad a number? [duplicate] - javascript

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I want a pattern like this:- GT-000001. This pattern gets incremented when a new record is inserted.
So I get values from my DB like this:
var pattern = 'GT-';
var init = 00000;
var recordnumber = 1; // This value i get dynamically.
var result = pattern + init + recodnumber;
But I get result = GT-01. I want result to be GT-000001. How to get this result?

The below example works for recordnumber upto 6 digits. outputing 'GT-000001', 'GT-000012', or 'GT-123456' based on the value of recordnumber
var pattern = 'GT-';
var recordnumber = 1; // This value i get dynamically.
var result = pattern + ('00000' + recordnumber).slice(-6);
console.log(result);

The reason you get that result is that you have
var init = 00000;
Note that the zeroes are not in quotes. That is effectively the same as:
var init = 0;
and so when you put it in the string, you get just the one zero.
If you want five zeroes, you need to use a string:
var init = "00000";
If you're trying to zero-pad, in general, this question and its answers that Matt found may be helpful.
But the short version:
var pattern = 'GT-';
var init = "000000"; // Note there are six of these, not five
var recordnumber = 1; // This value i get dynamically.
var result = String(recordnumber);
result = pattern + init.substring(result.length) + result;

Your init is number type, it is already truncated to 0 on assignment.
You need to add leading zeros manually:
function leadzeros(n, size) {
var s = n+"";
while (s.length < size) s = "0" + s;
return s;
}
var pattern = 'GT';
//var init = 00000; // <- here is 'init' is 0 already, so you can drop it
var recordnumber = 1; // This value i get dynamically.
var result = pattern + leadzeros(recodnumber, 5);

Related

how do I add two variables by javascript [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
the code below concatenates the two variables instead of adding them to get one value. any help on how to correct this?
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
You can use Number() to convert values to number
function calculatetotal1() {
var mal = Number(document.getElementById('<%=txtadults.ClientID%>').value);
var child = Number(document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
Parsing both variables as float should to the trick.
<script type="text/javascript">
function calculatetotal1() {
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
You need to convert those values to number before adding them using the + operator. There are several ways of doing that, but you can use parseInt or parseFloat for this:
var mal = document.getElementById('<%=txtadults.ClientID%>').value;
var child = document.getElementById('<%=txtnumchilderen.ClientID%>').value;
var res = parseFloat(mal) + parseFloat(child);
document.getElementById('<%=txttotal.ClientID%>').value = res;
You are getting input values from textbox and the datatype of textbox value by default is string. So your current code is just considering it as string and doing concatenation.
Try using parseFloat() function for both values.
Try the following code.
function calculatetotal1() {
var mal = parseFloat (document.getElementById('<%=txtadults.ClientID%>').value);
var child = parseFloat (document.getElementById('<%=txtnumchilderen.ClientID%>').value);
var res = mal + child;
document.getElementById('<%=txttotal.ClientID%>').value = res;
}
In JavaScript, + operator acts like concatenation and add the values
Like below
Var x = 2 + 3 // will be 5
Var y = '2' + 3 // will be 23 as string

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

How to find sum of integers in a string using JavaScript

I created a function with a regular expression and then iterated over the array by adding the previous total to the next index in the array.
My code isn't working. Is my logic off? Ignore the syntax
function sumofArr(arr) { // here i create a function that has one argument called arr
var total = 0; // I initialize a variable and set it equal to 0
var str = "12sf0as9d" // this is the string where I want to add only integers
var patrn = \\D; // this is the regular expression that removes the letters
var tot = str.split(patrn) // here i add split the string and store it into an array with my pattern
arr.forEach(function(tot) { // I use a forEach loop to iterate over the array
total += tot; // add the previous total to the new total
}
return total; // return the total once finished
}
var patrn = \\D; // this is the regular expression that removes the letters
This is not a valid regular expression in JavaScript.
You are also missing a closing bracket in the end of your code.
A simpler solution would be to find all integers in the string, to convert them into numbers (e.g. using the + operator) and summing them up (e.g. using a reduce operation).
var str = "12sf0as9d";
var pattern = /\d+/g;
var total = str.match(pattern).reduce(function(prev, num) {
return prev + +num;
}, 0);
console.log(str.match(pattern)); // ["12", "0", "9"]
console.log(total); // 21
you have some errors :
change var patrn = \\D with var patrn = "\\D"
use parseInt : total += parseInt(tot);
function sumofArr(arr){ // here i create a function that has one argument called arr
var total = 0; // I initialize a variable and set it equal to 0
var str = "12sf0as9d" // this is the string where I want to add only integers
var patrn = "\\D"; // this is the regular expression that removes the letters
var tot = str.split(patrn) // here i add split the string and store it into an array with my pattern
arr.forEach(function(tot){ // I use a forEach loop to iterate over the array
total += parseInt(tot); // add the previous total to the new total
})
return total; // return the total once finished
}
alert(sumofArr(["1", "2", "3"]));
https://jsfiddle.net/efrow9zs/
function sumofArr(str) {
var tot = str.replace(/\D/g,'').split('');
return tot.reduce(function(prev, next) {
return parseInt(prev, 10) + parseInt(next, 10);
});}
sumofArr("12sf0as9d");

Get max value of similar items in array with Javascript

I have an array like this:
["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"]
and I want to get a final array that will group similar values that changes from each other only by the last numbers of the string ("13rq8", "13rq6", "13rq4", "13rq2", "13rq12", "13rq10"), and return only the biggest values like the example below:
["13dl", "12dl", "13rq12"]
Can you help me please resolve this in Javascript?
Thank You!
Use an object (ex. tagNum) to keep track of the largest value of each prefix, and use regular expression to extract the prefix and trailing value:
var l = ["13rq8", "13rq6", "13rq4", "13rq2", "13dl", "12dl", "13rq12", "13rq10"];
var tagNum = {};
l.forEach(function(x) {
var m = x.match(/^(.*?)(\d*)$/);
var tag = m[1];
var num = parseInt("0" + m[2]);
if (tagNum[tag] === undefined || tagNum[tag] < num) tagNum[tag] = num;
});
var l2 = [];
for (var tag in tagNum) {
var num = tagNum[tag];
if (num) l2.push(tag + num);
else l2.push(tag);
}
console.log(l2);

Categories

Resources