I want to create an array and add a string to the array at zero index. I want to divide the string into separate letters (suppose I have the string java; I want to convert it into j,a,v,a). Is there any predefined methods for arrays in JavaScript?
Asked
Active
Viewed 278 times
0
Ben
- 51,770
- 36
- 127
- 149
user1813959
- 17
- 1
- 5
4 Answers
2
Splitting a string is as easy as :
"hello".split("")
In order to insert an array into a array at a certain index, you have to use splice. For example:
var array = [1,2,3,4],
hello = "hello".split("");
array.splice.apply(array, [0, 0].concat(hello));
The last line isn't that easy to understand at first. In javascript you can use apply on any function to call a function with parameters as array.
All it's doing is taking 0 element at index 0 in array and inserting the array hello at this position. You should read more about split and splice.
Splitting on an empty string will split on any character. But you can pass regex to split etc. So it's quite powerful.
Loïc Faure-Lacroix
- 13,220
- 6
- 67
- 99
0
Use split() and join() to achieve your requirement.
var xArray=[];
//Inserting a string at 0th index of an array
xArray[xArray.length] = "JAVA";
//Splitting that String with empty and joining the returned array with ","
xArray[xArray.length - 1] = xArray[xArray.length - 1].split("").join(",")
alert(xArray[xArray.length - 1]); //J,A,V,A
Rajaprabhu Aravindasamy
- 66,513
- 17
- 101
- 130