Parsing plain data with Javascript (JQuery)
Well , I have this text in a Javascript Var:
GIMP Palette
Name: Named Colors
Columns: 16
#
255 250 250 snow (255 250 250)
248 248 255 ghost white (248 248 255)
245 245 245 white smoke (245 245 245)
220 220 220 gainsboro (220 220 220)
255 250 240 floral white (255 250 240)
253 245 230 old lace (253 245 230)
250 240 230 linen (250 240 230)
250 235 215 antique white (250 235 215)
255 239 213 papaya whip (255 239 213)
And What I need is to cut it in lines and put them in one Array , after that i must separate each number and the rest in an string. I'm getting crazy searching functio开发者_JS百科ns to do that but now i can't see anyone in Javascript.
modified
End expected format will be first the next:
array[0]='255 250 250 snow (255 250 250)'
Then i wanna take it and extract each line into some vars to use them:
colour[0]=255;
colour[1]=250;
colour[2]=250;
string=snow (255 250 250);
(the vars will be reused with each line)
It would work something like this (try it out, printing the resulting array of objects in JSON format):
var lines = text.split('\n'),
colors = [];
for(var i = 0; i < lines.length; ++i) {
var splitLine = lines[i].match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)/);
if(splitLine) {
colors.push({
red: +splitLine[1],
green: +splitLine[2],
blue: +splitLine[3],
colorName: splitLine[4]
});
}
}
Then you can, for example, access the first color's red channel value using colors[0].red
.
I think this might work:
function cvtGimpPalette(p) {
var oneline = /^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/g;
var rv = [];
p.replace(oneline, function(_, r, g, b, comment) {
rv.push({ r: r, g: g, b: b, string: comment});
});
return rv;
}
That should give you an array, with each element of the array being an object with the colors split out from the text. If you want the colors in an array, you'd replace that "rv.push" line with:
rv.push({ colours: [r, g, b], string: comment });
I ran this and it works quite well.
var str = "GIMP Palette\n\
Name: Named Colors\n\
Columns: 16\n\
#\n\
255 250 250 snow (255 250 250)\n\
248 248 255 ghost white (248 248 255)\n\
245 245 245 white smoke (245 245 245)\n\
220 220 220 gainsboro (220 220 220)\n\
255 250 240 floral white (255 250 240)\n\
253 245 230 old lace (253 245 230)\n\
250 240 230 linen (250 240 230)\n\
250 235 215 antique white (250 235 215)\n\
255 239 213 papaya whip (255 239 213)";
var reg = /(\d{1,3}) (\d{1,3}) (\d{1,3}) (.+ \(\d{1,3} \d{1,3} \d{1,3}\))/,
pieces = str.split('\n'),
match,
result = [];
for (var i = 4; i < pieces.length; i++) {
match = reg.exec(pieces[i]);
if (match !== null) {
result.push({
r: +match[1],
g: +match[2],
b: +match[3],
string: match[4],
toString: function() {
return this.r + " " +
this.g + " " +
this.b + " " +
this.string;
}
});
}
}
alert(result);
JS Fiddle Source
var color = array[i].replace(/\s+/g,' ').split(' ');
var str = color.splice(-4).join(' ');
console.log(color); console.log(str);
精彩评论