Question: How to convert each character in the string to an array using javascript
Answer: Here we have seven methods for converting all the characters of any string into an array. We will also solve this problem by using 'split()' function and without using 'split()' function.
First: using 'split()' function.
var myString = "RustcodeWeb"; var myArray = myString.split(''); console.log(myArray); console.log(myArray[8]);
Output:
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Second: using 'from()' function.
var myString = "RustcodeWeb"; var myArray = Array.from(myString); console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Third: using 'push()' function and 'for loop'.
var myString = "RustcodeWeb"; var myArray = []; for (const tempString of myString) { myArray.push(tempString); } console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Fourth: using spread syntax(...), 'new Array()' and Array Initializer concept.
var myString = "RustcodeWeb"; var myArray = new Array(...myString); // Creating New Array And String To Array Conversion console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Fifth: using spread syntax(...), Array Initialization with string to array Conversion concept.
var myString = "RustcodeWeb"; var myArray = [...myString]; // Array Initialization with string to array Conversion console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Sixth: using spread syntax(...), Array Initialization, "return arguments" concept.
var myString = "RustcodeWeb"; function arrayFunction() { return arguments; } var myArray = arrayFunction(...myString); console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
Seventh: using "Object.assign([], string)" concept.
var myString = "RustcodeWeb"; var myArray = Object.assign([], myString); console.log(myArray); console.log(myArray[8]);
Output:.
["R", "u", "s", "t", "c", "o", "d", "e", "W", "e", "b"] "W"
We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.
Comments
Post a Comment