For some reason my code returns "0111" when the returned value should be 3 adding the numbers together.
Is there a better way to write this so it adds the value of the input text?
var p = $(".p").val();
var r = $(".r").val();
var d = $(".d").val();
var s = $(".s").val();
var checkability = p + r + d + s;
alert(checkability)
You are concatenating strings you need to cast it to numeric. val() return data as string, or explicitly use parseInt(var, 10) or parseFloat based on your type.
Simple way is t use unary + operator prefixing the variable:
var checkability = +p + +r + +d + +s;
Fiddle
Sure, the easiest thing is to coerce the string values into integers like:
var p = +$(".p").val();
var r = +$(".r").val();
var d = +$(".d").val();
var s = +$(".s").val();
jsFiddle example
You could also use the longer parseInt() function like var p = parseInt( $(".p").val(), 10);
Use parseInt to make them integers
var p = parseInt($(".p").val(),10);
var r = parseInt($(".r").val(),10);
var d = parseInt($(".d").val(),10);
var s = parseInt($(".s").val(),10);
var checkability = p + r + d + s;
alert(checkability)
Related
I am trying to do a very simple calculation of 11.000 + 5.000 expecting to have 16.000 then dividing it by 2 expecting to get a final result of 8.000. It was working ok in another language (ahk) but I'm having unexpected results trying it in javascript (Not a Number, 5.5 and 5.50025)
How should I write this calculation to get the expected result of 8.000?
var A = "11.000";
var B = "5.000";
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000
Here A + B is doing actually string concationation not simple addition. you need to change them to number first
var A = "11.000";
var B = "5.000";
var resultA = ((+A) + (+B)) / 2;
console.log(resultA);
// You can use toFixed if you three decimal digit
console.log(resultA.toFixed(3));
Here A and B are in string format and Once you do A + B the result will be "11.000" + "5.000" = "11.0005.000" (string concatenation). So to get expected result you should parse each string value to Float/Int then do the addition operation.
Try, var resultD = (parseFloat(A) + parseFloat(B)) /2
Just remove the quotation marks and the vars will be recognized as number not as string so you'll get the expected result.
var A = 11.000;
var B = 5.000;
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000
I'm catching the date from a form as a string and pass it to a API-Request-URL.
The date string is in this format: 16022019
But the API accepts a date string only in this format: 20190216.
Basically, in my string, I need to change the position of the first 2 characters with the position of the last 4 characters.
I fixed the issue as follow:
let date = e.target.elements.date.value; // 16022019
const dateFirst = date.slice(0, 2);
const dateMiddle = date.slice(2, 4);
const dateLast = date.slice(4, 8);
date = `${dateLast}${dateMiddle}${dateFirst}`; // 20190216
But I'm not sure if this is a good solution. Is there any better way to achieve the same result?
I don't see any problem with your method. in case you want to know alternate you can try this.
This uses regex to capture digits of desired width and than places to desired place.
let str = `16022019`
console.log(str.replace(/(\d{2})(\d{2})(\d{4})/,"$3$2$1"))
You can also use destructuring assignment and rest parameter syntax to do it.
const str = `16022019`;
[d, d1, m, m1, ...year] = str.split("");
const dateStr = [...year,m,m1,d,d1].join("");
console.log(dateStr);
How about mapping the positions:
[/*y*/ 4, 6, /*m*/ 2, /*d*/ 0].reduce((acc, p) => acc + date.slice(p, p + 2), "")
You could also do something like this by using Array#reverse and Array#join.
const data = "16022019"
const res = data.split(/(\d{2})(\d{2})(\d{4})/).reverse().join("");
console.log(res);
using substring
var a = '16022019';
console.log(a.substring(a.length - 4, a.length) + a.substring(2, 4) + a.substring(0, 2))
using substr
var a = '16022019';
console.log(a.substr(a.length-4,4)+a.substr(2,2)+a.substr(0,2))
Here is a way working with dates:
function yyyymmdd() {
var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var yyyymmdd = y + m + d;
return yyyymmdd;
}
console.log(yyyymmdd("16022019")) // outputs 20190216
References: https://codereview.stackexchange.com/q/184459
I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));
Say I have two string variables:
a = 'LOVE';
b = '....';
How do I use regex (or whatever else is fastest) to combine a + b to make:
c = 'L.O.V.E.';
In my case, both strings are 4 characters long, always, and the second string is not a fixed character, I just made it a dot to make it look clearer on screen.
You can simply loop through the longer string and in each iteration append one character from both strings to your resulting string. I don't think you need any regular expression there:
a = 'LOVE';
b = '....';
var combinedString = '';
var largerLength = Math.max( a.length, b.length );
for( var i = 0; i < largerLength; i++ )
{
combinedString += a.charAt(i) + b.charAt(i);
}//for()
console.log( combinedString );
The above code will work for strings of any length. In case, you know beforehand that both strings are exactly 4 characters long, I think the fastest and most efficient way would be:
a = 'LOVE';
b = '....';
var combinedString = a.charAt[0] + b.charAt[0] + a.charAt[1] + b.charAt[1] + a.charAt[2] + b.charAt[2] + a.charAt[3] + b.charAt[3];
console.log( combinedString );
You could use Array#reduce for it
var a = 'LOVE',
b = '....';
c = a.split('').reduce(function (r, v, i) {
return r + v + b[i];
}, '');
console.log(c);
How to combine a + b via regex:
var a = "LOVE", b = "....";
var result = a.replace(/./g, (match, i) => match + b[i]);
console.log(result);
There is no need of regex for your problem. You can simply do it with the help of for loop
a = 'LOVE';
b = '....';
var result = '';
var length = Math.max( a.length, b.length );
for( var i = 0; i <+ length-1; i++ )
{
result = result + a.charAt(i);
result = result + b.charAt(i);
}
alert("Result of combined string is :"+ result);
You can use array functions on array likes (in this example strings) to iterate over it's items.
var a = 'LOVE',
b = '....',
c = Array.prototype.map
.call(a, (v, i) => v + b[i]).join('');
console.log(c);
If your second string is always composed of dots, instead of repeating same characters in string, try something like this:
Using Delimiter
var a = "LOVE";
var delimeter = ".";
var result = a.split("").join(delimeter) + delimeter;
console.log(result)
Array convert + manual concatenation
As an alternate to string.charAt, you can try something like this:
Note: you should do a1[i] || "" for cases where value can be undefined. Also you should use .toString() to avoid cases where both values are numeric and result will be addition instead of concatenation.
var a = 'LOVE';
var b = '....';
var c = ",,,,,,,,,,,";
function mergeStr(a, b) {
var a1 = a.split("");
var b1 = b.split("");
var len = Math.max(a.length, b.length)
var r = "";
for (var i = 0; i < len; i++) {
r += (a1[i] || "").toString() + (b1[i] || "").toString();
}
return r;
}
console.log(mergeStr(a,b))
console.log(mergeStr(a,c))
I am trying to implement the following code but the value returned to the id on page is populated with the NaN (Not a Number) error. Has anyone got any suggestions what I can do here? I have been battling this for over an hour now, so your assistance would be appreciated.
setInterval( function(){
var b = $('input#ien_val').val();
var ien;
for (ien = 0; ien < b; ien++) {
var encuser = parseInt($('#enutt'+ien).html());
var enteam = parseInt($('#enttotalday'+ien).html());
var enoffset = (encuser/enteam)*100;
$('#tten' + ien).html(enoffset + '%');
}
},2000);
As per comments below I have added an example of my issue here http://jsbin.com/tobilonepu/1/
Youre trying to loop through $('#enttotalday'+ien) but there is only one value there so its casuing the issue. working code:
setInterval( function(){
var b = $('input#ien_val').val();
var ien;
for (ien = 1; ien < b; ien++) {
// add parseInt
var encuser = parseInt($('#enutt'+ien).val());
// add parseInt
var enteam = parseInt($('#enttotalday').val());
var enoffset = (encuser/enteam)*100;
$('#tten' + ien).html(enoffset + '%');
}
},2000);
jsbin here - http://jsbin.com/nivoxuwufa/1/
You should parse dom value to number use parseInt or parseFloat. Based on that the code should look like this.
setInterval( function(){
var b = $('input#ien_val').val();
var ien;
for (ien = 0; ien < b; ien++) {
// add parseInt
var encuser = parseInt($('#enutt'+ien).val());
// add parseInt
var enteam = parseInt($('#enttotalday'+ien).val());
var enoffset = (encuser/enteam)*100;
$('#tten' + ien).html(enoffset + '%');
}
},2000);
Hope it could help you. Cheers.
Since you are performing arithmatic operations, you need to make sure that the values that you have are either Number/integer/float and not string. .val() generally gets you a string.
Replace:
var encuser = $('#enutt'+ien).val();
var enteam = $('#enttotalday'+ien).val();
with:
var encuser = Number($('#enutt'+ien).val());
var enteam = Number($('#enttotalday'+ien).val());
Instead of Number(), you can use parseInt() or parseFloat() as per your requirement.
Readup:
Number() | MDN
parseInt() | MDN
parseFloat() | MDN
You have to transform encuser and enteam to numbers first. Try something like this
setInterval( function(){
var b = $('input#ien_val').val();
var ien;
for (ien = 0; ien < b; ien++) {
var encuser = parseFloat($('#enutt'+ien).val());
var enteam = parseFloat($('#enttotalday'+ien).val());
var enoffset = (encuser/enteam)*100;
$('#tten' + ien).html(enoffset + '%');
}
},2000);
Readmore about parseInt, parseFloat & Number:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
Update
Working: http://jsbin.com/mezamakopi/2/edit