Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform Javascript Array into delimited String

I have a Javascript string array with values like A12, B50, C105 etc. and I want to turn it into a pipe delimited string like this: A12|B50|C105...

How could I do this? I'm using jQuery (in case that helps with some kind of builtin function).

like image 370
Alex Avatar asked Jul 20 '10 05:07

Alex


People also ask

How do you split 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.

What does .join do in JavaScript?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Which method can you use character other than comma to separate values from array?

In that case, the split() method returns an array with the entire string as an element. In the example below, the message string doesn't have a comma (,) character.


3 Answers

var pipe_delimited_string = string_array.join("|");

Array.join is a native Array method in Javascript which turns an array into a string, joined by the specified separator (which could be an empty string, one character, or multiple characters).

like image 79
Daniel Vandersluis Avatar answered Oct 21 '22 18:10

Daniel Vandersluis


No need for jQuery. Use Javascripts join() method. Like

var arr = ["A12", "C105", "B50"],
    str = arr.join('|');

alert(str);
like image 11
jAndy Avatar answered Oct 21 '22 18:10

jAndy


Use JavaScript 'join' method. Like this:

Array1.join('|')

Hope this helps.

like image 1
NawaMan Avatar answered Oct 21 '22 17:10

NawaMan