Question: I have a hidden field and I add string to it, separated by semicolon. How I can I check the duplication when adding a new string?

I am doing as

```
function AddToHiddenField(source, hdnFieldId)
    {
        var srcList = document.getElementById(source);
        var hdnFieldSubstring = document.getElementById(hdnFieldId);
        var len = srcList.length;
        hdnFieldSubstring.value = '';
        for(var i = 0; i < len; i++) 
        {
            if (srcList.options[i] != null) 
            {
                if (hdnFieldSubstring.value  == "")
                {
                    hdnFieldSubstring.value  = srcList.options[i].text;
                }
                else 
                {    
                    hdnFieldSubstring.value = hdnFieldSubstring.value + ";" + srcList.options[i].text;
                }                    
            }
        }
    }

```

How can I check a string already exists in hdnFieldSubstring before added to it (in javascript)?

Answer: 
This would be simpler if you always put the semi colon in the value. I.e.

```
if (srcList.options[i] && hdnFieldSubstring.value.indexOf(srcList.options[i].text + ";") == -1)
    hdnFieldSubstring.value += srcList.options[i].text + ";";

```

Now you can always search for the string with a semi-colon on the end.

* Don't forget to make sure that the strings don't include semi-colons already.
* If the last semi-colon will cause you problems then strip it off just before submitting the form by putting a handler on the submit button.
Honestly I wouldn't persist the data in the field, I'd do it in an array. 

```
function AddToHiddenField(source, hdnFieldId)
{
    //create storage if it doesn't exist
    if (typeof(window.hiddenFieldData)=='undefined')
    {
      window.hiddenFieldData = [];
    }

    var srcList = document.getElementById(source);
    for(var i=0, n=srcList.length, value; i<n; i++)
    {
      if (srcList.options[i] != null) 
      {
        var value = srcList.options[i].text;
        /* 
        ignores duplicates by virtue of overwriting index - 
        if you didn't want to just overwrite you'd wrap this with:
          if(typeof(window.hiddenFieldData[value])=='undefined')         
        */
        window.hiddenFieldData[value] = value;
      }
    }

    //serialise storage to hidden field
    document.getElementById(hdnFieldId).value = window.hiddenFieldData.join(';');
}

```

Rule of thumb: if you have to deserialise a string to maintain integrity, you shouldn't be using a string as data storage.

*note: if your original source was in a hidden field for some reason, I'd still do it like this but I'd init my array with a string.split*