Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to split and modify a string in NodeJS?

How to split and modify a string in NodeJS?

Problem

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?

Problem courtesy of: Burak

Solution

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 courtesy of: Michał Miszczyszyn

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to split and modify a string in NodeJS?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×