1

I have following string

var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

What is the best way to fetch largeimage value which is "/uploads/photo/image/3256/zoom_1303-1.jpg" Let me tell you guyz currently i am using this.(which is very basic)

var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";
var b = a.split('largeimage:')[1].split("'")[1];
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
error-404
  • 229
  • 4
  • 18

4 Answers4

0

Have only this idea.

var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

var b = a.split(',');

var c = b[2].split("'");

var img = c[1];

console.log(img););     // "/uploads/photo/image/3256/zoom_1303-1.jpg"

JSFIDDLE.

loveNoHate
  • 1,549
  • 13
  • 21
0

You have two choice here:

  1. Make your string a valid JSON - to do this you will need to wrap gallery, largeimage, smallimage with apostrophe. so it would look like this:

    var validJSONstring = '{"gallery": "gal", "smallimage": "/uploads/photo/image/3256/big_1303-1.jpg", "largeimage": "/uploads/photo/image/3256/zoom_1303-1.jpg"}';
    
    var validJSONObject = JSON.parse(validJSONstring);
    console.log(validJSONObject.largeimage);
    

Then you have to parse it to JSON and get the property name.

  1. Split the string where separator sign is "," comma, loop through results and split each result when separator sign is ":" and check for the property you are looking for.
Scription
  • 646
  • 3
  • 12
  • 21
0

Here's a rough implementation of parsing a valid JS object. It doesn't support nested objects, but for the sample string it will work correctly.

function parseObject(objString) {
    var obj = {},
        parts,
        part,
        splitPart;

    // Remove leading and trailing {}s
    objString = objString.trim().replace(/^{|}$/g, '');
    parts = objString.split(','); // split properties into an array

    for (part in parts) {
        splitPart = parts[part].split(':'); // split key/value

        // .join for values containing ':', then the regex removes leading and trailing quotes and spaces
        obj[ splitPart[0] ] = splitPart.slice(1).join(':').replace(/^\s*['|"]\s*|\s*['|"]\s*$/g, '');
    }

    return obj;
}
Joe
  • 15,669
  • 4
  • 48
  • 83
-1
var a = "{gallery: 'gal', smallimage: '/uploads/photo/image/3256/big_1303-1.jpg', largeimage: '/uploads/photo/image/3256/zoom_1303-1.jpg'}";

var jsontemp = a.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
var obj = JSON.parse(correctjson);
var c = obj.largeimage;

JSFiddle

For turning into valid json, I used the solution from this post: https://stackoverflow.com/a/24462870/888177

Community
  • 1
  • 1
Stefan
  • 3,850
  • 2
  • 26
  • 39