从字符串中获取特定值

时间:2014-09-18 10:21:11

标签: javascript

我有以下字符串

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

获取largeimage值的最佳方法是" /uploads/photo/image/3256/zoom_1303-1.jpg" 让我告诉你guyz目前我正在使用它。(这是非常基本的)

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];

4 个答案:

答案 0 :(得分:0)

只有这个想法。

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.

答案 1 :(得分:0)

你有两个选择:

  1. 使您的字符串成为有效的JSON - 要做到这一点,您需要使用撇号包装gallery,largeimage,smallimage。 所以它看起来像这样:

    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);
    
  2. 然后你必须将它解析为JSON并获取属性名称。

    1. 拆分分隔符号为"的字符串,"逗号,遍历结果并在分隔符号为"时分割每个结果:"并检查您正在寻找的房产。

答案 2 :(得分:0)

这是解析有效JS对象的粗略实现。它不支持嵌套对象,但对于示例字符串,它将正常工作。

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;
}

答案 3 :(得分:-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

为了变成有效的json,我使用了这篇文章的解决方案:https://stackoverflow.com/a/24462870/888177