Cris69
Cris69

Reputation: 590

convert a string into a javascript array with regular expression

I have a long string containing text information about a multi-page image file. Here is an example:

test.tif[0] TIFF 1962x2668+0+0 DirectClass 1-bit 12.8M 0.000u test.tif[1] TIFF 
1952x2688+0+0 DirectClass 1-bit 12.8M 0.000u test.tif[2] TIFF 1650x2200+0+0 
DirectClass 1-bit 12.8M 0.000u 0:01 etc..

I need to convert the string into an array of image informations like this:

[
    'test.tif[0] TIFF 1962x2668+0+0 DirectClass 1-bit 12.8M 0.000u',
    'test.tif[1] TIFF 1952x2688+0+0 DirectClass 1-bit 12.8M 0.000u',
    'test.tif[2] TIFF 1650x2200+0+0 DirectClass 1-bit 12.8M 0.000u 0:01',
    etc..
]

Probably with some sort of regular expression it is possible to separate the part of the string starting with [x], including the name of the left side that can change every time. Or maybe there is a better way to do that ?

Upvotes: 0

Views: 74

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208475

var array = string.split(/ (?=test\.tif\[\d+\])/);

This uses a lookahead to split on each space that is followed by test.tif[<number>].

To handle different extensions, you could change the tif portion of the regex to [a-zA-Z]+ to allow anything or something like (?:tif|gif|png) to allow only specific extensions.

Upvotes: 4

Related Questions