We help IT Professionals succeed at work.

javascript array looping and string concatenation

VirusMinus
VirusMinus asked
on
I have a string of product options thats one huge string where the options are separated by the ~ character. total options are over 3000.

Whats the fastest (best performing) way to make this into a select with each of the product options going into <option>product option</option> elements?

I can use jQuery also
Comment
Watch Question

I would split the string by "~" and then loop through using jquery's .each() function.  Here is an example.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
      <head>
            <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
			<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
			<style>
				* {margin:0;padding:0;}

				html, body
				{

					font-family: Arial;
					font-size: .95em;
					height: 100%;
					width: 100%;
					border: 0;
					padding: 0;
					margin: 0;
					line-height:1em;
					font-weight:normal;
				}


			</style>




      </head>
</head>

<body>

		<select id="mySelect"></select>

		<script type="text/javascript">

			var myString = "Item1~Item2~Item3~Item4"
			var myStringArr = myString.split("~")

			$(document).ready(function(){
				$(myStringArr).each(function(index,item){
					$("#mySelect").append("<option value='" + item + "'>" + item + "</option>")
				});
			});

	  </script>

</body>



</html>

Open in new window

Top Expert 2007

Author

Commented:
Nope...can't prove it.  But, it's pretty darn efficient.
However - your question is about parsing a concatenated string, not concatenating a string.  So, is this *more* efficient than parsing using javascript and some sort of i++ loop - don't know.
Top Expert 2007

Author

Commented:
Not exactly but it helped