Objectif Lune joins Upland Software.Learn more >

Back to all How-tos

Splitting a string into many elements

In this How-To we’re going to take a single field and split it into different elements. This is useful to create lists, menus, etc.

For this trick to work, the first thing is to find a character to split on. The most common characters that are used in lists are the comma (,), space ( ), pipe (|) and semi-colon (;).

Let’s assume we have a data field with the following contents: blue,red,yellow,turquoise,white,black. We’ll be turning this into a simple bullet point list, or a <ol> with one <li> for each item in the list.

Here’s a simple script to do this, using the field name colors. The script should have the list’s ID as selector (e.g. #color_list ) so that results in the script holds the list element.

var colors = record.fields.colors.split(",");

for(var i = 1, length = colors.length; i < length; i++) {
	results.append("<li>" + colors[i] + "</li>");
}

 

Going a bit further - list in list

Here’s a fun way to go a little further on the idea above, which we can do if there are two separators: the one to split the list, and the one to provide a key and value. So let’s do something like the Dynamically add options to a drop-down trick, but this time, with a single, double-separated string: bl|Blue,yl|Yellow,rd|Red,tq|Turquoise,wt|White,bk|Black

If we have a <select> element with the ID of color_list, the script with the selector #color_list goes as such:

var colors = record.fields.colors.split(",");

for(var i = 1, length = colors.length; i < length; i++) {
	var color_data = colors[i].split("|");
	results.append('<option value="' + color_data[0] + '">' + colors_data[1] + "</option>");
}

Leave a Reply

Your email address will not be published. Required fields are marked *