Date Input | adding dash after the date - javascript

I am trying to add the - after the second digit(date) on keypress for the date. Suppose if the user types the today s date as 24 after which - should be added and then after typing month "11" it should type - automatically.
Similarly, while backspacing/removing the character, dash to be removed.
Pattern : pattern="[0-9]{2}-[0-9]{2}-[0-9]{4}"
Function
onChangeText = (text) => {
text = text
.replace(/^[a-zA-Z\-]+$/g, '')
.replace(/^(\d\d\d\d)(\d)$/g, '$1-$2')
.replace(/^(\d\d\d\d\-\d\d)(\d+)$/g, '$1-$2')
.replace(/[^\d\-]/g, '')
}

here is you can do something like this, but you need first declare a variable and get the value after the regx. when you're done with regx then declare a varible and store the value in it then apply below logic!
Example
here we go!
let data = '123233';
let newData = ''; // declare the golbal variable to put dash
for ( let str = 0; data.length > str; ++str )
{
if( str % 2 === 0 && str !== 0) // finding even number and also zero
newData += '-',newData += data[str - 0];
else
newData += data[str]
}
console.log(newData)
apply this logic in your code, i hope you will get your expection!
Thanks!

Related

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

format decimal in javascript

i would like to format decimal values to specific format as like
1.23 should be shown as 0001.23 using javascript. is there any specific functions like toPrecision(), tofixed() in javascript to handle these kind of formatting or any pointers to go ahead with any solutions?
here preceeding decimal is dynamic one.
for example :
i have 2 values :
first value : 99.4545
second value : 100.32
in this second value has higher length (3)before decimal and first value has higher length after decimal(4). so subtracted result(0.8655) of this should be formatted as ###.#### (000.8685)
thank you
Just make a function that does what you want it to. Here is an example you can expand on if you want.
function pad(num, padSize){
var numString = "" + num.split('.')[0];
if(num.length < padSize){
var numZeroes = padSize-num.length;
var zeroes = "";
while(numZeroes){zeroes += "0"; numZeroes--;}
return zeroes + num;
}else return num;
}
if you want to lpad some 0 onto 1.23 you can do the following
var value = 1.23
value = ("0000000"+ value).slice(-7);
Change the -7 to be whatever you want the total string length including the decimal point to be.
Added after question edit
The above should handle your question pre-edit but for the rest of it you'll need something like this.
var formatNum = function (num, preLen, postLen) {
var value = num.split("."),
padstring = "0";
padLen = (preLen > postLen)?preLen:postLen;
for (i = 0; i < padLen; i++) {
padstring += padstring;
}
if (typeof(value[1]) === "undefined") {
value[1] = "0";
}
return ((padstring + value[0]).slice(-preLen)+ "." + (value[1] + padstring).substring(0,postLen));
}
This takes the number you want formatted and the lengths you want each string to be on either side of the '.'. It also handles the case of an integer.
If you want it to output any other cases such as returning an integer, you'll have to add that in.
Try to use a string, like "000" + some value

how to append double digit if user passed single digit value using jquery

I'm working on jquery.
i want to check the validation on todate and from date.
want to convert my string into double digit (need to add 0 if user enter single digit value)
how can i give double digit as user enter single digit value into textbox?
expected output is
var HourPerWeek = $("#Hour").val();
-- if user enter value 2 i need to convert it into 02
var MinPerWeek = $("#Min").val();
-- if user enter value 1 i need to convert it into 01
Instead of length of string ?
function returnDoubleDigits(str) {
return str.length === 1 ? '0' + str : str;
}
e.g.
var HourPerWeek = returnDoubleDigits($("#Hour").val());
Fiddle
Would this work,just check the string length and then add a zero if it is shorter than 2
var HourPerWeek;
if ($("#Hour").val().length < 2){
HourPerWeek = "0"+ $("#Hour").val();
}
else{
HourPerWeek = $("#Hour").val();
}
You will have to add the 0 to the beginning of the string manually like in this example:
String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
var HourPerWeek = $("#Hour").val().paddingLeft('00');
Explanation: You can call paddingLeft on any string. It will add the chars, that you pass as an argument to the left of the string and return a string with exactly the length of the given argument. More examples:
''.paddingLeft('00') // returns '00'
'1'.paddingLeft('00') // returns '01'
'11'.paddingLeft('00') // returns '11'
'111'.paddingLeft('00') // returns '11'
'1'.paddingLeft(' ') // returns ' 1'
Have this as a function which checks for length of passed parameter.
function returnTwoDigit(var Data){
if (Data.length != 2) {
if (Data.length == 1) {
Data= "0" + Data;
}
return Data
}

Trouble adding leading zeroes to submitted form data in javascript

I looked through here last night for some examples on adding leading zeroes with JavaScript and I couldn't get any of them to work for my purposes. I want to do this with the data once you hit the submit button. It is running a set of checkers when it does this and this is what I have included, but I grab the POST data in a test php page and the field I am trying to fix shows "undefined"
I need the number of digits to always be 7, regardless of whether they entered a four or five digit number. Leading zeroes need to be added. Not sure if I am kind of close or way off target with this:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
}
offidlength = custform.optionaldata10.value.length;
if (offidlength <7) {
custform.optionaldata10.value = pad(custform.optionaldata10.value, 7);
}
You forgot the return statement.
return str;
Should be at the end of the function.
edit function should look like:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
You can make your expression simpler, if you always want 7 digits-
var offid= custform.optionaldata10.value, L= 7-offid.length;
if(L>0) custform.optionaldata10.value= '0000000'.substring(0, L)+offid;

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories