(ง •̀_•́)ง Ming's blog

Converting in JavaScript

References

Content

String to Array

split

var str = "The quick brown fox jumps over the lazy dog.";
var words = str.split(" ");
console.log(words[3]); // expected output: "fox"
var chars = str.split("");
console.log(chars[8]); // expected output: "k"
var strCopy = str.split();
console.log(strCopy); // expected output: Array ["The quick brown fox jumps over the lazy dog."]

Array.from

console.log(Array.from("foo"));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

Array to String

join

var elements = ["Fire", "Air", "Water"];
console.log(elements.join()); // expected output: "Fire,Air,Water"
console.log(elements.join("")); // expected output: "FireAirWater"
console.log(elements.join("-")); // expected output: "Fire-Air-Water"