Using split() and for loop
When split() is called, it searches a string for a specific pattern and divides the string into multiple substrings. These substrings are placed into an array and the array is then returned:
- split: The pattern that describes where to split.
First, assume your string has a list of numbers which is separated by semicolons. Then use split() to achieve an array of splitted strings. After that convert each string in the array to number type and push it to the destination array:
let s = "1;3;5;7"; let a = s.split(";"); let res = ; for (i of a) res.push(Number(i)); console.log(res);
If a string contains multiple separators instead of one, you cannot declare as above in the split()’s parameter. All you have to do is to use a regex to represent your list of separators (you can read more at our tutorial). For example:
let s = "1,3;5:7 9.9"; let a = s.split(/[;,:\s]+/); let res = ; for (i of a) res.push(+i); console.log(res);
The above code tries to split a string by 4 separators: a semicolon(;), a comma (,) a colon(:) and a whitespace but not a dot (as it represents a floating point number). We also introduced another way of converting a string to a number using + operator inside the for loop.
[1, 3, 5, 7, 9.9]
This method is not only easy to understand but also easy to implement. However, there is also an approach that can help you do this with just a line of code:
Using split() and map()
- callbackFn: The callbackFn function is called for each element, and its returned value is added to newArray.
When the map method is called, a new array is created that contains the results of applying the callbackFn function provided to every element of the calling array:
let s = "1;3;5;7"; res = s.split(";").map(Number) console.log(res);
Number() converts values of other types into numbers. Constants and methods in the Number constructor help you work with numbers. Number(value) converts a string, floating-point number, boolean value, or null value to the Number type. If the input value can’t be converted, NaN is returned.
Maybe you are interested:
Name of the university: HCMUT