[英]Javascript how to split string characters into variables
I am trying to split a string's characters into variables like this: 我正在尝试将字符串的字符分成这样的变量:
<script>
var string = "hello";
//After splitting:
var stringAt1 = "h";
var stringAt2 = "e";
var stringAt3 = "l";
var stringAt4 = "l";
var stringAt5 = "o";
</script>
Could somebody give an example of how this can be done? 有人可以举例说明如何做到这一点吗?
Split according to the non-word boundary \\B
( which matches between two word characters or two non-word characters ). 根据非单词边界
\\B
( 在两个单词字符或两个非单词字符之间匹配)进行拆分。
var string = "hello"; alert(string.split(/\\B/))
Then assign the splitted parts to separate variables. 然后将分割后的部分分配给单独的变量。
String.prototype.split() function can be used for requirement. String.prototype.split()函数可用于要求。
The
split()
method splits aString
object into an array of strings by separating the string into substrings.split()
方法通过将String
对象拆分为子字符串,将String
对象拆分为String
数组。
Usage 用法
var string = "hello"; var arr = string.split(''); var stringAt1 = arr[0]; alert(stringAt1)
In ES5 there's no other way than 在ES5中,除了
var splitted = "abc".split("");
var char0 = splitted[0];
var char1 = splitted[1];
etc
In ES6 it's much easier: 在ES6中,它要容易得多:
var [char0, char1, char2] = "abc";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.