Reputation: 5440
I have 3 strings "a","b","c" in javascript array "testarray".
var testarray=new Array("a","b","c");
and then I am printing the value of testarray using javascript alert box.
alert(testarray);
The result will be like a,b,c
All these strings are separated by "," character. I want to replace this "," with some other character or combination of two or more characters so that the alert box will show something like a%b%c
or a%$b%$c
Upvotes: 25
Views: 105117
Reputation: 23208
use testarray is getting converted in string using testarray.toString()
before alert. toString internally joining these items using ',' as separator. you can convert it into string using Array.join
and pass own separator.
alert(testarray.join("%"));
Upvotes: 4
Reputation: 17839
you can iterate through the array and insert your characters
var testarray=new Array("a","b","c");
var str;
for (var i = 0; i < testarray.length; i++) {
str+=testarray[i]+"%";
}
alert(str);
Upvotes: 8
Reputation: 165961
Use the join
method:
alert(testarray.join("%")); // 'a%b%c'
Here's a working example. Note that by passing the empty string to join
you can get the concatenation of all elements of the array:
alert(testarray.join("")); // 'abc'
Side note: it's generally considered better practice to use an array literal instead of the Array
constructor when creating an array:
var testarray = ["a", "b", "c"];
Upvotes: 88