I am trying to process some input data in JavaScript whereby I need to replace the occurrences of all string tokens (in the form "ID1", "ID2", "ID3", ...) with a string that wraps the original token. For example "ID1" becomes "table['ID1']". However if the original token is wrapped in quotes (single or double) it must be ignored.

For example the input string:

```
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";

```

should become:

```
"table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0']."

```

I can currently get some of the way using the following code ([Try it on jsbin.com here](http://jsbin.com/retoloro/1/edit)):

```
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";

var expected = "table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].";

// assume 15 is the max number of ids. we search backwards.
for( i=15 ; i>=0 ; i-- )
{
    var id = "ID" + i;

    var regex = new RegExp( "[^\"\']" + id + "", 'g' );

    input = input.replace( regex, "table['" + id + "']" );
}

if( input == expected )
    alert( 'success :)' );

```

This produces the output:

```
ID10 "ID0" FOO 'ID0' table['ID0']#table['ID10'] BARtable['ID1']table['ID0'].

```

It seems close to working, however the first id (ID10) gets ignored and the first character before a match gets lost.

Can anybody please advise how to process this correctly, thanks.