Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing commas from javascript array

Tags:

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

like image 675
Basim Sherif Avatar asked Oct 11 '12 08:10

Basim Sherif


People also ask

How do you remove commas from a string?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do I remove a comma from a number in typescript?

replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.

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.


1 Answers

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"];
like image 135
James Allardice Avatar answered Oct 16 '22 22:10

James Allardice