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
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.
replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With