Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript how to convert string to array and array to string

In JavaScript and Jquery how to convert the string to array and same array convert to string and check them using typeof method in JavaScript.

like image 604
Raghul Rajendran Avatar asked Aug 18 '15 08:08

Raghul Rajendran


People also ask

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I turn a string array into strings?

Create an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.

Which method is used to convert arrays to strings in JavaScript?

JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.


3 Answers

From String to Array you can Use split() Method

var str = "How are you doing today?";
var res = str.split(" ");

console.log(res); // How,are,you,doing,today? it will print

From Array to String you can use Join() method or toString() Method

like image 130
stackover flow Avatar answered Oct 21 '22 12:10

stackover flow


var arr = "abcdef".split(''); // creates an array from a string

var str = arr.join(''); // creates a string from that above array
like image 26
Jaromanda X Avatar answered Oct 21 '22 10:10

Jaromanda X


If you want do it manually, without any JavaScript methods. Try the below

String to Array

var str = "STRING";
var arr = [];
for(int i=0; i<=str.length; i++)
    arr[i] = str.charAt(i);

Array to String

var str = "";
var arr = ["S","T","R","I","G"];
for(int i=0; i<=arr.length; i++)
    str +=arr.charAt(i);
like image 1
RevanthKrishnaKumar V. Avatar answered Oct 21 '22 11:10

RevanthKrishnaKumar V.