2 Replies Latest reply on Jul 4, 2014 8:28 AM by [Jongware]

# Convert string array to array of numbers

Hello all,

I need to help with converting string array "15,0,25,40" loaded from txt file to array of numbers so I can use it e.g. with geometricBounds like this:

```tx1.geometricBounds = [15,0,25,40];
```

I have tryed to search the internet but none of sample codes worked

Thanks very much in advance to everyone willing to help...

• ###### 1. Re: Convert string array to array of numbers

Hi,

It depends on the way you are filling array with contents. I.e. this way:

string = "2,12,12,24";

mArr = string.split(",");

should work

Jarek

• ###### 2. Re: Convert string array to array of numbers

There are several different ways of doing this. One way, for example, is to use a Regular Expression to match all digits in this string:

```txt = "15,0,25,40";
numbers = txt.match(/\d+/g);
alert (numbers.length);    // Should show '4'
```

The 'match' command returns an array of matches, and since you are only interested in the digits themselves, '\d+' should grab all 4 elements. To use these four elements (note: 'match' returns strings, so these are not yet really "numbers"!), you can do something like

```app.selection[0].geometricBounds = [ Number(numbers[0]), Number(numbers[1]), Number(numbers[2]), Number(numbers[3]) ];
```

where the function 'Number(numbers[x])' converts the text string "15" into a real number. This conversion is not really necessary here, for Javascript, but nevertheless recommended.

If you need to "do" something with the numbers, that is the way to do it. For instance, if the values in txt are "left x, top y, width, height", you need to calculate the geometric bounds as follows:

```app.selection[0].geometricBounds = [ Number(numbers[1]),
Number(numbers[0]),
Number(numbers[1]) + Number(numbers[3]),
Number(numbers[0]) + Number(numbers[2]) ];
```

-- and here you see when you need to convert to a "real" number. If you don't do that, Javascript will add the string "15" to the string "25", and you get the result "1525"!

.. That said .. ... if (and only if!) the format of your input is exactly the format InDesign expects for a certain value, such as 'geometricBounds', you can do this:

```txt = "15,0,25,40";
app.selection[0].geometricBounds = eval('['+txt+']');
```

which works because the 'eval' command evaluates its string, and with the square brackets before and after a comma-separated list of numbers, it returns this as a properly formed array. A nice trick, but I suggest you use the "proper way" as described above until you have more programming confidence. Tricks like this one are very hard to debug if things go wrong, and for the moment you are better off using the clear, documented, more proper way.