Javascript string and array conversion Summary
This article will share with you the simple and practical functions of converting strings into arrays and arrays into strings in Js. For more information, see.
Convert array to string
1. join () method
?
1 2 3 4 |
Var s = ["a", "d", "a", "f", "g", "f", "s", "g"]; S. join () // "a, d, a, f, g, f, s, g" S. join ("") // "a d a f g f s g" S. join (''); // adafgfsg |
String to array
1. call () method
?
1 2 3 |
Var str = "adafgfsg "; Var strArr = Array. prototype. slice. call (str, 0 ); Console. log (strArr ); |
Result: ["a", "d", "a", "f", "g", "f", "s", "g"]
2. Regular Expression
?
1 2 3 4 5 6 |
Var str = "adafgfsg "; Var strArr = str. replace (/(.)(? =.)/G, '$1,'). split (','); Console. log (strArr ); Var str = "adafgfsg "; Var strArr = str. match (/\ w/g ); Console. log (strArr ); |
Result: ["a", "d", "a", "f", "g", "f", "s", "g"]
3. directly use the split () method
?
1 2 3 |
Var str = "adafgfsg "; Var strArr = str. split (''); Console. log (strArr ); |
Result: ["a", "d", "a", "f", "g", "f", "s", "g"]
The above is all the content summarized in this article. I hope you will like it.