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?
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.
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.
To split a String in TypeScript, you can use String. split() function.
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; });
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With