25

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

2
  • I am being over picky here but declare arrays using var testarray= ["a","b","c"] rather than var testarray=new Array("a","b","c");it reads easier an avoids a few potential issues. Commented Oct 11, 2012 at 8:50
  • thanks for the tip. will figure it out next time :) Commented Oct 11, 2012 at 8:55

3 Answers 3

88

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"];
Sign up to request clarification or add additional context in comments.

Comments

8

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);

Comments

4

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("%"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.