Similar to or like the function:
list("String")
'''
return: ['S','t','r','i','n','g']
'''
Is there a Javascript equivalent of the function?
Similar to or like the function:
list("String")
'''
return: ['S','t','r','i','n','g']
'''
Is there a Javascript equivalent of the function?
The closest equivalent in all cases of what is passed to list()
would be using the spread syntax from ES6. For older versions of JavaScript, you can use string.split('')
for a character array. Note that .split('')
won't work with characters that use surrogate pairs.
function list(iterable) {
return [...iterable];
}
console.log(list('String'));
Use String#split
method with empty string separator as an argument which converts a string into a character array.
"String".split('')
console.log(
"String".split('')
)
For latest browsers, use Array.from
method or spread syntax.
// Using Array.from
var arr = Array.from("String")
// Using spread syntax
var arr = [..."String"]
console.log(
Array.from("String")
)
console.log(
[..."String"]
)
Use the split method, "Hello world!".split('')
.
console.log(
"Hello world!".split('')
)
If you want to convert a String into an Array with each element being a character of the string, you can use String.prototype.split()
:
"String".split('') //['S', 't', 'r', 'i', 'n', 'g']