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
Related
Hello everyone and my problem faced is when user key in Malaysian Identity Card "930402084401", I want the key in number to automatically add - to become "930402-08-4401".
When User key in 930402084401
What I want in my textbox => 930402-08-4401
I try to refer to the code where the code will automatically add space every 4 numbers, but I totally have no idea how to change the code.
document.getElementById('creditSpace').addEventListener('input', function(e) {
var target = e.target,
position = target.selectionEnd,
length = target.value.length;
target.value = target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<label><input id="creditSpace"> CC Details </label>
Hope someone can solve my problem. Thank you.
var s = '930402084401';
var t = s.replace( /(\d{6})(\d{2})(\d{4})/, '$1-$2-$3' ); // 930402-08-4401
You can do it with a simple for loop:
let str = '930402084401';
const myFunc = str => {
let r = '';
for (let i = 0; i < str.length; i++) {
r += str[i];
if (i == 5 || i == 7) r += '-';
}
return r;
};
myFunc(str);
Try some thing like this. Use map, slice and join
const format = (str, last = 0) =>
[6, 2, 4].map((num) => str.slice(last, (last += num))).join("-");
const str = "930402084401";
console.log(format(str));
The fastest way is also the simplest, just create separate groups of numbers and add in the - as necessary. If you want 6, 2, 4, then:
const key = '930402084401';
const text = `${key.slice(0, 6)}-${key.slice(6, 8)}-${key.slice(8)}`;
console.log(text);
Str = "930402084401";
formattedStr = Str.slice(-Str.length, 6) + "-" + Str.slice(-6,-4) + "-" + Str.slice(-4)
console.log(formattedStr);
I need a regular expression to be used in credit card form
the rule is simple, the format must be MMYY.
I could achieve that with this regular expression.
/^(0[1-9]|1[0-2])\d{2}$/
Now am researching to apply validation to make YY 19 for the current year
and in future years.
Maybe its hard to make it dynamic, but i can replace the string 19 from
current year in javascript, so now I just want it fixed for 19 and above.
Example of valid MMYY:
0126
1220
0119
Example of In Valid MMYY
0101
1111
1218
Here is reference of what i have now
Example shared for my reg exp looks like
Given a year for which that year and future years should pass, it'd be a bit tedious to dynamically construct such a regular expression. Consider using a capture group instead, and then just check whether the captured YY is greater than or equal to the limit:
const yearLimit = 19; // or pass this as an argument if you want
const re = /^(?:0[1-9]|1[0-2])(\d{2})$/;
const match = str.match(re);
if (!match) {
return false;
}
const year = Number(match[1]);
return year >= yearLimit;
const validate = (str) => {
const yearLimit = 19; // or pass this as an argument if you want
const re = /^(?:0[1-9]|1[0-2])(\d{2})$/;
const match = str.match(re);
if (!match) {
return false;
}
const year = Number(match[1]);
return year >= yearLimit;
};
console.log(
validate('1234'),
validate('1212')
);
^(?:0[1-9]|1[0-2])(\d{2})$ means
^ - Match start of string
(?:0[1-9]|1[0-2]) - Match 01-12: either
0[1-9] - Leading 0, followed by a number 1 to 9, or
1[0-2] - Leading 1, followed by a number 0 to 2
(\d{2}) - Match and capture any two digits
$ - Match end of string
Below code will work if you want to solve it by regex only.
const currentYear = 19;
const currentDecade = currentYear/10;
const unitPlaceCurrentYear = currentYear%10;
regex_string = `^(0[1-9]|1[0-2])(1[${unitPlaceCurrentYear}-9]|[${currentDecade+1}-9][0-9])$`
var re = new RegExp(regex_string);
inputs = ['0126','1220','0119','0101','1111','1218'];
inputs.map((str) => {
let match = str.match(re);
if (match) console.log('matched: ' + str);
else console.log('Did not match: ' + str);
});
Here is the dynamic solution for your answer
var date = new Date()
var a = date.getFullYear().toString().substr(2,2).split('')
var monthRegex = "(0[1-9]|1[0-2])"
var yearRegex1 = "([" + a[0] + "-9][" + a[1] + "-9])"
var yearRegex2 = "([" + (parseInt(a[0], 10) + 1) + "-9][0-9])"
var regex2 = new RegExp("^" + monthRegex + yearRegex1 + "|" + yearRegex2 + "$");
console.log(regex2.test('1218'))
console.log(regex2.test('1219'))
console.log(regex2.test('1239'))
Hope this helps
Date can be in any format 25.10.2018 or 25.10.18 or 25-12-2018 or 25-12-18, need to change this date to 25/10/2018 this format only.
The user can input date in any above format, I need to distinguish first in which format then needs to change its format to the desired format.
I do not want to use any 3rd Party JavaScript file.
You can easily do this using momentjs.
Check below working examples:
let d1 = "25.10.2018";
console.log(moment(d1, "DD.MM.YYYY").format("DD/MM/YYYY"));
let d2 = "25.10.18";
console.log(moment(d2, "DD.MM.YY").format("DD/MM/YYYY"));
let d3 = "25-12-2018";
console.log(moment(d3, "DD-MM-YYYY").format("DD/MM/YYYY"));
let d4 = "25-12-18";
console.log(moment(d4, "DD-MM-YY").format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
So your original date have included special character like .,- .So you can split with that characters and I add 0 for your month and date 1 digit.For year format , use new Date to get correct year even two digit have provided ....
var d = '12-4-88'; // '25.10.2018'; or 25.10.18 or 25-12-2018
d = d.split(/[.\-_]/);
d.forEach((v,k) => {
if(v < 10) d[k] = 0 + v;
if(k == 2 && v.length == 2) {
var year = new Date(v+"-01-01");
d[k] = year.getFullYear();
}
})
console.log(d[0] + '/' + d[1] + '/' + d[2]);
You will need Date to preserve full year as two digits year value evaluates invalid date.
function parse(str) {
var result = {
'input': str,
'output': null
};
var tmp = str.split(/[\.|\-]/);
if (tmp && 3 === tmp.length) {
if (2 === tmp[2].length) {
tmp[2] = new Date().getFullYear().toString().substr(0, 2) + tmp[2];
}
if (1 === tmp[1].length) {
tmp[1] = '0' + tmp[1];
}
result.output = tmp.join('/');
}
return result;
}
console.log(parse("25.10.2018"));
console.log(parse("25.10.18"));
console.log(parse("25-10-2018"));
console.log(parse("25-10-18"));
console.log(parse("25.1.2018"));
console.log(parse("05.10.2018"));
function replaceAll(string, search, replacement) {
return string.replace(new RegExp(search, 'g'), replacement);
};
const newDate = replaceAll(oldDate, '.', '/');
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
"25.10.2018".replaceAll(".", "/");
I need to create a string like this to make works the mapserver request:
filterobj = "POLYGON((507343.9 182730.8, 507560.2 182725.19999999998, 507568.60000000003 182541.1, 507307.5 182563.5, 507343.9 182730.8))";
Where the numbers are map coordinates x y of a polygon, the problem is with Javascript and OpenLayer what I have back is an array of numbers, How can I remove just the ODD commas (first, third, fifth...)?
At the moment I've created the string in this way:
filterobj = "POLYGON((" +
Dsource.getFeatures()[0].getGeometry().getCoordinates() + " ))";
And the result is:
POLYGON((507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8));
It's almost what I need but, I need to remove the ODD commas from the Dsource.getFeatures()[0].getGeometry().getCoordinates() array to make the request work, how can I do that?
The format that you need is WKT, and OpenLayers comes with a class that allows you to parse its geometries as WKT easily, as below:
var wktFormatter = new ol.format.WKT();
var formatted = wktFormatter.writeFeature(Dsource.getFeatures()[0]);
console.log(formatted); // POLYGON((1189894.0370893013 -2887048.988883849,3851097.783993299...
Look at code snippet :
Help method : setCharAt ,
Take all commas ,
take all odds commas with i % 2 == 0
// I need to start from somewhere
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var POLYGON = [507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8];
var REZ = "";
REZ = POLYGON.toString();
var all_comma = [];
for(var i=0; i<REZ.length;i++) {
if (REZ[i] === ",") all_comma.push(i);
}
for(var i=0; i<all_comma.length;i++) {
if (i % 2 == 0 ) {
REZ = setCharAt(REZ,all_comma[i],' ');
}
}
console.log(REZ);
// let return nee element intro POLYGON
// reset
POLYGON = REZ.split(',');
console.log(POLYGON);
What about this:
const str = Dsource.getFeatures()[0].getGeometry().getCoordinates()
// str = "1,2,3,4,5,6"
str.split(',').map((v, i) => {
return (i % 2) ? v : v + ','
}).join(' ')
// "1, 2 3, 4 5, 6"
There are a couple of ways to go, both involve getting rid of whitespace first. The first matches coordinate pairs, removes the comma, then pastes them back together.
The second splits into individual numbers, then formats them with reduce. Both should be ECMA-262 ed5 (2011) compatible but I don't have an old enough browser to test them.
var s = '507343.9, 182730.8,507560.2, 182725.19999999998, 507568.60000000003, 182541.1, 507307.5, 182563.5,507343.9, 182730.8';
var re = /\d+\.?\d*,\d+\.?\d*/g;
// Solution 1
var x = s.replace(/\s/g,'').match(re).map(function(x){return x.replace(',',' ')}).join();
console.log(x);
// Solution 2
var t = s.replace(/\s/g,'').split(',').reduce(function (acc, v, i) {
i%2? (acc[acc.length - 1] += ' ' + v) : acc.push(v);
return acc;
}, []).join(',');
console.log(t);
One approach would be using Array.reduce():
var input = '1.0, 2.0, 3.0, 4.0, 5.0, 6.0';
var output = input
.split(',')
.reduce((arr, num, idx) => {
arr.push(idx % 2 ? arr.pop() + ' ' + num : num);
return arr;
}, [])
.join(',');
// output = '1.0 2.0, 3.0 4.0, 5.0 6.0'
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)