How do you get a string to a character array in Ja

2019-01-02 19:49发布

How do you get a string to a character array in JavaScript?

I'm thinking getting a string like "Hello world!" to the array ['H','e','l','l','o',' ','w','o','r','l','d','!']

8条回答
孤独总比滥情好
2楼-- · 2019-01-02 20:22
> "Hello world!".split('')
["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

Just split it by an empty string.

See String.prototype.split() MDN docs.

查看更多
看淡一切
3楼-- · 2019-01-02 20:23

Since this question is originally asked more than five years ago, people are still misopetating this type of task. As hippietrail suggests, meder's answer can break surrogate pairs and misinterpret “characters.” For example:

// DO NOT USE THIS!
> '                                                                    
查看更多
素衣白纱
4楼-- · 2019-01-02 20:24

You do not need to do anything. It is already array of char.

查看更多
姐姐魅力值爆表
5楼-- · 2019-01-02 20:25

You can also use Array.from.

var m = "Hello world!";
console.log(Array.from(m))

This method has been introduced in ES6.

Reference

Array.from

查看更多
浮光初槿花落
6楼-- · 2019-01-02 20:33

This is an old question but I came across another solution not yet listed.

You can use the Object.assign function to get the desired output:

Object.assign([], "Hello, world!")
[ 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!' ]

Not necessarily right or wrong, just another option.

Object.assign is described well at the MDN site.

查看更多
回忆,回不去的记忆
7楼-- · 2019-01-02 20:33

Without using any function:

function key(e) {
  if (e.keyCode === 13) {
    var st = document.getElementById('txt').value;
    var char = [];
    for (var i = 0; i < st.length; i++) {
      char.push(st[i]);
    }
    document.getElementById('chr').innerHTML = char;
  }
}
<input type="text" id="txt" onkeypress="key(event)"></input>
<p>Click Enter for char array:</p>
<p id="chr"></p>

查看更多
登录 后发表回答