Chuck Tomasi
Tera Patron

find_real_file.pngLet me introduce you to two of my favorite little JavaScript methods join() and split(). They save me lots of time managing arrays and strings. If you aren't familiar with join() and split(), then let's take a closer look at what some people do instead, the issues with it, and how these two methods can make your life so much simpler.

All too often I see people putting together comma (or other character) separated values in a string variable with a loop something like this:



var answer = '';
var arr = ['red', 'blue', 'green'];

for (var i=0; i < arr.length; i++) {
answer += arr<i> + ',';
}

// Result: answer=red,blue,green,


Yeah, I used to do that for a while also. It's common when you don't know about some of the available native JavaScript methods.

The problem with the above approach is that you have that nasty trailing comma! When you go to parse the resulting string apart again, you end up with an extra (null) element in the array. Sure, you could put an if statement in there to test the length and leave off the comma, but that's just a hack in my opinion. Why not use someone else's elegant code to put it all together like this?



var arr = ['red', 'blue', 'green'];
var answer = arr.join(',');

// Result: answer=red,blue,green


Want to use a different character to delimit your values? Just change the character passed to join! Simple.

The inverse of the join operation is split() - clever, huh? It is commonly used when you are given a list of comma (or other character) separated values and want to save them in to an array. For example:



var str='Detroit,London,Tokyo';

var arr = str.split(',');

// Result: arr=['Detroit', 'London', 'Tokyo'];


Now you have a convenient way to put arrays together in to a character delimited string, and take them apart again. No loops, no conditions, just simple, easy-to-use, built-in methods.

2 Comments