3

Similar to or like the function:

list("String")
'''
return: ['S','t','r','i','n','g']
'''

Is there a Javascript equivalent of the function?

Skully Kra
  • 41
  • 1
  • 3
  • You mean you want char array? Use split function eg: "String".split('') – user1211 Feb 08 '17 at 04:08
  • For latest browser use `Array.from` – Pranav C Balan Feb 08 '17 at 04:37
  • @AbdennourTOUMI I don't think it's a duplicate, because [`list()`](https://docs.python.org/2/library/functions.html#list) has more uses in Python than getting character arrays. It's a general purpose converter from iterable types to list types. – 4castle Feb 08 '17 at 05:05

5 Answers5

4

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'));
Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106
2

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"]
)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0
var str = "String"    
str.split('');

That should do it

azizj
  • 3,428
  • 2
  • 25
  • 33
0

Use the split method, "Hello world!".split('').

console.log(
  "Hello world!".split('')
)
Teodorico Levoff
  • 1,641
  • 2
  • 26
  • 44
0

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']
hackerrdave
  • 6,486
  • 1
  • 25
  • 29