Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 652
Burak Avatar asked Feb 28 '13 11:02

Burak


People also ask

How do you split a string in node JS?

The split() function is a string function of Node. js which is used to split string into sub-strings. This function returns the output in array form. Parameters: This function accepts single parameter separator which holds the character to split the string.

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.

How do I split a string in TypeScript?

To split a String in TypeScript, you can use String. split() function.


1 Answers

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);
like image 155
Michał Miszczyszyn Avatar answered Oct 11 '22 14:10

Michał Miszczyszyn