开发者

How do I split a string into an array of characters? [duplicate]

开发者 https://www.devze.com 2023-03-15 06:51 出处:网络
This question already has answers here: How to get character array from a string? (14 answers) Closed 5 years ago.
This question already has answers here: How to get character array from a string? (14 answers) Closed 5 years ago.
var s = "overpopulation";
var ar = [];
ar = s.split();
alert(ar);

I want to string.split a word into array of characters.

Th开发者_如何学编程e above code doesn't seem to work - it returns "overpopulation" as Object..

How do i split it into array of characters, if original string doesn't contain commas and whitespace?


You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without split:

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'


Old question but I should warn:

Do NOT use .split('')

You'll get weird results with non-BMP (non-Basic-Multilingual-Plane) character sets.

Reason is that methods like .split() and .charCodeAt() only respect the characters with a code point below 65536; bec. higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters.

'
0

精彩评论

暂无评论...
验证码 换一张
取 消