简体   繁体   中英

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 ).

 var string = "hello"; alert(string.split(/\\B/)) 

Then assign the splitted parts to separate variables.

String.prototype.split() function can be used for requirement.

The split() method splits a String object into an array of strings by separating the string into substrings.

Usage

 var string = "hello"; var arr = string.split(''); var stringAt1 = arr[0]; alert(stringAt1) 

In ES5 there's no other way than

var splitted = "abc".split("");
var char0 = splitted[0];
var char1 = splitted[1];
etc

In ES6 it's much easier:

var [char0, char1, char2] = "abc";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM