How to cut off individual items in a javascript list
Entrance:
dates = [201701, 201702, 201703]
I need output as [2017-01, 2017-02, 2017-03]
I tried using slice method in javascript but it fails
for (var i in dates) {
dates[i].slice(0, 4) + "-" + dates[i].slice(4);
}
It fails.
+3
swat
source
to share
2 answers
You just forgot toString()
:
var dates = [201701, 201702, 201703];
for (var i = 0; i < dates.length; i++) {
console.log(dates[i].toString().slice(0, 4) + "-" + dates[i].toString().slice(4));
}
+3
Arg0n
source
to share
You can use Number#toString
it String#replace
for the dates you want.
var dates = [201701, 201702, 201703],
result = dates.map(a => a.toString().replace(/(?=..$)/, '-'));
console.log(result);
Or use String#split
.
var dates = [201701, 201702, 201703],
result = dates.map(a => a.toString().split(/(?=..$)/).join('-'));
console.log(result);
Both ES5 examples
var dates = [201701, 201702, 201703];
console.log(dates.map(function (a) { return a.toString().replace(/(?=..$)/, '-'); }));
console.log(dates.map(function (a) { return a.toString().split(/(?=..$)/).join('-'); }));
+2
Nina scholz
source
to share