Converting String To Array Of Characters And Numbers To Array Of Integers In Javascript
Table of contents
No headings in the article.
There are times when we need to convert string to array of characters and numbers to array of integers for many purposes. There are many ways of doing that. However, the methods are not the same in terms of readability and efficiency. In this post, I will share with you the method I use.
1. Converting string to array of character
// convert string into array of characters
let str = 'hello people'
let strArr = [...str]
console.log(strArr)
Output:
[
'h', 'e', 'l', 'l',
'o', ' ', 'p', 'e',
'o', 'p', 'l', 'e'
]
2. Converting number to string of integers
// convert number into array of digits
let num = 12345
num = num.toString()
let digitStrArr = [...num]
let numArr = digitStrArr.map(item => parseInt(item))
console.log(numArr)
Output:
[ 1, 2, 3, 4, 5 ]
3. Manipulation of string using array of characters:
let string = 'help from someone'
// let us try to replace space character with underscore (_)
let charArr = [...string]
for(i in charArr){
if(charArr[i] === ' '){
charArr[i] = '_'
}
}
console.log(charArr.join(''))
Output:
help_from_someone
I hope the article is helpful and don’t hesitate to share your ways with me.