How to split and modify a string in NodeJS?
I have a string :
var str = "123, 124, 234,252";
I want to parse each item after split and increment 1. So I will have:
var arr = [124, 125, 235, 253 ];
How can I do that in NodeJS?
Use split
and map
function:
var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });
Notice +val
- string is casted to a number.
Or shorter:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });
edit 2015.07.29
Today I'd advise against using +
operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number
call:
var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) {
return Number(val) + 1;
});
console.log(arr);
edit 2017.03.09
ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:
var str = "123, 124, 234,252";
var arr = str.split(",").map(val => Number(val) + 1);
console.log(arr);
var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
arr[i] = ++arr[i];
}