Okay, not the hottest topic in the world of dev, but a common one nonetheless!

Let’s say that you’re creating a fun game that lets kids pick their favorite animal and puts a picture of their face on the animal (c’mon, million dollar idea, right).

You’ll start off with a select element with a list of animals to choose from. To populate that select element, you Google “list of animal names”. The first result contains a great list of animal names from A-Z.

Now, how do you convert that list into HTML <option> tags? There are two approaches here:

Hard Coded HTML

Believe it or not, you can use your favorite spreadsheet tool to create the HTML.

  • Copy your list from the website you found (or whatever your source is) and paste it into column B of the spreadsheet.
  • In Column A, enter <option> and copy/paste it to the last row.
  • In Column C, enter <option> and copy/paste it to the last row (by now, you might see where I’m going with this).
  • Export the spreadsheet as a CSV file.
  • Open the CSV file in your code editor, or text editor.
  • Find/replace the commas with, well, nothing.
  • You’ve got your HTML!

Use a Loop in Your Scripting Language

If you’re familiar with Regular Expressions, you can use your favorite code editor’s find/replace dialog with it’s regular expression option.

  • Copy your list from the website you found (or whatever your source is) and paste it into your code editor.
  • Open your find/replace dialog and make sure “use regular expressions” is checked.
  • Enter \R in the find box. In most tools, this signifies a line break.
  • Enter ',' into the replace box (adjust this based on your scripting languages syntax for an array).
  • Once you do the find/replace, you’ll notice that the list has been converted to a single line, with each option delimited by ‘,’
  • From there, just add a leading (' and trailing ') (depending on your languages syntax) and you’ve got your array!

The Easier Way

As a dev, I need to do this type of thing very often. So I created a little online Line Break Remover tool to make this quick and painless. I keep it in a folder in my bookmark bar.

Just enter a single quote in the Wrap lines with field, a comma in the Replace line break with character field, then paste your list into the first text box. Voila!

Leave a Reply

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