Object type of string read from file split on delimiter

I’m reading in a string from a file and then splitting it on a delimiter. However, the array elements are not Javascript strings. When I try to split one of them on a delimiter I get unexpected results.

var gridConfigurationRawData = IJ.openAsString(folder + IMAGE_GRID_CONFIGURATION_FILENAME); 
var arrayOfData = gridConfigurationRawData.split("\n"); 
dataLine = arrayOfData[i].split(","); 

var possibleImageName = dataLine[0];
//possibleImageName = "1039607_hnsccTMAB_nuclei_One.svs"
print("possibleImageName: " + possibleImageName);
print("typeof possibleImageName: " + (typeof possibleImageName));
var imageNameParts = possibleImageName.split(".");
print("imageNameParts.length: " + imageNameParts.length);
var extension = imageNameParts[imageNameParts.length - 1];
print("extension: " + extension);


possibleImageName: 1039607_hnsccTMAB_nuclei_One.svs
typeof possibleImageName: object
imageNameParts.length: 0
extension: undefined

However, if I uncomment possibleImageName = "1039607_hnsccTMAB_nuclei_One.svs", I get

possibleImageName: 1039607_hnsccTMAB_nuclei_One.svs
typeof possibleImageName: string
imageNameParts.length: 2
extension: svs

How do I fix?

This fixed it:

var possibleImageName = new String(dataLine[0]);

But why do I need to be so heavy handed? Is there a better way to read in a file so that it comes in as Javascript manipulatable strings?

Because Javascript is loosely typed.

Note that this is unrelated to ImageJ - you will almost certainly receive faster and more thorough answers on a dedicated venue (e.g. using the Javascript tag on StackOverflow - which is where I personally go for all my programming questions).

As to your question, I have limited Javascript experience, but I recommend reading more1,2 about types and type coercion in Javascript.

1 Like

It’s just confusing because the code mixes Javascript objects and Java objects. Perhaps this is just a limitation of the Rhino engine. There appears to be a Rhino method for reading files. I’ll try and see if it works in the ImageJ interpreter. There is also a plain vanilla file reader in Javascript now that can read files uploaded by the browser.

But that doesn’t seem to be part of Rhino.

@abalter Note that ImageJ is in the process of migrating to Java 8. So anything Rhino-specific you do in a script may not be supported a few months from now. The current JavaScript engine shipped with the JVM is Nashorn.

Good to know! Thanks!