How to split and modify a string in NodeJS?

Javascriptnode.js

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

var str = "123, 124, 234,252";
var arr = str.split(",");
for(var i=0;i<arr.length;i++) {
    arr[i] = ++arr[i];
}

Solution 3 - Javascript

If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.

If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):

_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:

I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:

const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBurakView Question on Stackoverflow
Solution 1 - JavascriptMichał MiszczyszynView Answer on Stackoverflow
Solution 2 - JavascriptmihaimmView Answer on Stackoverflow
Solution 3 - JavascriptAndrew FaulknerView Answer on Stackoverflow